FRE-600: Fix code review blockers

- Consolidated duplicate UndoManagers to single instance
- Fixed connection promise to only resolve on 'connected' status
- Fixed WebSocketProvider import (WebsocketProvider)
- Added proper doc.destroy() cleanup
- Renamed isPresenceInitialized property to avoid conflict

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
2026-04-25 00:08:01 -04:00
parent 65b552bb08
commit 7c684a42cc
48450 changed files with 5679671 additions and 383 deletions

View File

@@ -0,0 +1,37 @@
import type { Address } from 'abitype'
import { sign } from '../../accounts/utils/sign.js'
import type { Hex } from '../../types/misc.js'
import { concatHex } from '../../utils/index.js'
import type { ZksyncSmartAccount } from '../types/account.js'
import { toSmartAccount } from './toSmartAccount.js'
export type ToMultisigSmartAccountParameters = {
/** Address of the deployed Account's Contract implementation. */
address: Address
/** Array of Private Keys belonging to the owners. */
privateKeys: readonly Hex[]
}
/**
* Creates a [ZKsync Smart Account](https://docs.zksync.io/build/developer-reference/account-abstraction/building-smart-accounts)
* from a Contract Address and an array of Private Keys belonging to the owners.
*/
export function toMultisigSmartAccount(
parameters: ToMultisigSmartAccountParameters,
): ZksyncSmartAccount {
const { address, privateKeys } = parameters
return toSmartAccount({
address,
async sign({ hash }) {
return concatHex(
await Promise.all(
privateKeys.map((privateKey) =>
sign({ hash, privateKey, to: 'hex' }),
),
),
)
},
})
}

View File

@@ -0,0 +1,30 @@
import type { Address } from 'abitype'
import { sign } from '../../accounts/utils/sign.js'
import type { Hex } from '../../types/misc.js'
import type { ZksyncSmartAccount } from '../types/account.js'
import { toSmartAccount } from './toSmartAccount.js'
export type ToSinglesigSmartAccountParameters = {
/** Address of the deployed Account's Contract implementation. */
address: Address
/** Private Key of the owner. */
privateKey: Hex
}
/**
* Creates a [ZKsync Smart Account](https://docs.zksync.io/build/developer-reference/account-abstraction/building-smart-accounts)
* from a Contract Address and a Private Key belonging to the owner.
*/
export function toSinglesigSmartAccount(
parameters: ToSinglesigSmartAccountParameters,
): ZksyncSmartAccount {
const { address, privateKey } = parameters
return toSmartAccount({
address,
async sign({ hash }) {
return sign({ hash, privateKey, to: 'hex' })
},
})
}

63
node_modules/viem/zksync/accounts/toSmartAccount.ts generated vendored Normal file
View File

@@ -0,0 +1,63 @@
import type { Address } from 'abitype'
import { toAccount } from '../../accounts/toAccount.js'
import type { ErrorType } from '../../errors/utils.js'
import type { Hash, Hex } from '../../types/misc.js'
import { keccak256 } from '../../utils/index.js'
import { hashMessage } from '../../utils/signature/hashMessage.js'
import { hashTypedData } from '../../utils/signature/hashTypedData.js'
import { serializeTransaction } from '../serializers.js'
import type { ZksyncSmartAccount } from '../types/account.js'
import type { ZksyncTransactionSerializableEIP712 } from '../types/transaction.js'
export type ToSmartAccountParameters = {
/** Address of the deployed Account's Contract implementation. */
address: Address
/** Function to sign a hash. */
sign: (parameters: { hash: Hash }) => Promise<Hex>
}
export type ToSmartAccountErrorType = ErrorType
/**
* Creates a [ZKsync Smart Account](https://docs.zksync.io/build/developer-reference/account-abstraction/building-smart-accounts)
* from a Contract Address and a custom sign function.
*/
export function toSmartAccount(
parameters: ToSmartAccountParameters,
): ZksyncSmartAccount {
const { address, sign } = parameters
const account = toAccount({
address,
sign,
async signMessage({ message }) {
return sign({
hash: hashMessage(message),
})
},
async signTransaction(transaction) {
const signableTransaction = {
...transaction,
from: this.address!,
} as ZksyncTransactionSerializableEIP712
return serializeTransaction({
...signableTransaction,
customSignature: await sign({
hash: keccak256(serializeTransaction(signableTransaction)),
}),
})
},
async signTypedData(typedData) {
return sign({
hash: hashTypedData(typedData),
})
},
})
return {
...account,
source: 'smartAccountZksync',
} as ZksyncSmartAccount
}

318
node_modules/viem/zksync/actions/claimFailedDeposit.ts generated vendored Normal file
View File

@@ -0,0 +1,318 @@
import { type Address, parseAbi } from 'abitype'
import type { Account } from '../../accounts/types.js'
import { getTransaction } from '../../actions/public/getTransaction.js'
import { getTransactionReceipt } from '../../actions/public/getTransactionReceipt.js'
import { readContract } from '../../actions/public/readContract.js'
import {
type SendTransactionErrorType,
type SendTransactionParameters,
type SendTransactionReturnType,
sendTransaction,
} from '../../actions/wallet/sendTransaction.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { zeroHash } from '../../constants/bytes.js'
import { AccountNotFoundError } from '../../errors/account.js'
import { ClientChainNotConfiguredError } from '../../errors/chain.js'
import type { TransactionReceiptNotFoundErrorType } from '../../errors/transaction.js'
import type { GetAccountParameter } from '../../types/account.js'
import type {
Chain,
DeriveChain,
GetChainParameter,
} from '../../types/chain.js'
import type { Hash, Hex } from '../../types/misc.js'
import type { UnionEvaluate, UnionOmit } from '../../types/utils.js'
import {
decodeAbiParameters,
decodeFunctionData,
encodeAbiParameters,
encodeFunctionData,
type FormattedTransactionRequest,
isAddressEqual,
parseAccount,
} from '../../utils/index.js'
import { bootloaderFormalAddress } from '../constants/address.js'
import {
CannotClaimSuccessfulDepositError,
type CannotClaimSuccessfulDepositErrorType,
L2BridgeNotFoundError,
type L2BridgeNotFoundErrorType,
LogProofNotFoundError,
type LogProofNotFoundErrorType,
} from '../errors/bridge.js'
import type { ChainEIP712 } from '../types/chain.js'
import type { BridgeContractAddresses } from '../types/contract.js'
import type { ZksyncTransactionReceipt } from '../types/transaction.js'
import { undoL1ToL2Alias } from '../utils/bridge/undoL1ToL2Alias.js'
import { getDefaultBridgeAddresses } from './getDefaultBridgeAddresses.js'
import { getLogProof } from './getLogProof.js'
export type ClaimFailedDepositParameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
chainL2 extends ChainEIP712 | undefined = ChainEIP712 | undefined,
accountL2 extends Account | undefined = Account | undefined,
_derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,
> = UnionEvaluate<
UnionOmit<FormattedTransactionRequest<_derivedChain>, 'data' | 'to' | 'from'>
> &
Partial<GetChainParameter<chain, chainOverride>> &
Partial<GetAccountParameter<account>> & {
/** L2 client. */
client: Client<Transport, chainL2, accountL2>
/** The L2 transaction hash of the failed deposit. */
depositHash: Hash
}
export type ClaimFailedDepositReturnType = SendTransactionReturnType
export type ClaimFailedDepositErrorType =
| SendTransactionErrorType
| TransactionReceiptNotFoundErrorType
| CannotClaimSuccessfulDepositErrorType
| LogProofNotFoundErrorType
| L2BridgeNotFoundErrorType
/**
* Withdraws funds from the initiated deposit, which failed when finalizing on L2.
* If the deposit L2 transaction has failed, it sends an L1 transaction calling `claimFailedDeposit` method of the
* L1 bridge, which results in returning L1 tokens back to the depositor.
*
* @param client - Client to use
* @param parameters - {@link ClaimFailedDepositParameters}
* @returns hash - The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link ClaimFailedDepositReturnType}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync, mainnet } from 'viem/chains'
* import { claimFailedDeposit, publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const account = privateKeyToAccount('0x…')
*
* const hash = await claimFailedDeposit(client, {
* client: clientL2,
* account,
* depositHash: <L2_HASH_OF_FAILED_DEPOSIT>,
* })
*
* @example Account Hoisting
* import { createPublicClient, createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync, mainnet } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const walletClient = createWalletClient({
* chain: mainnet,
* transport: http(),
* account: privateKeyToAccount('0x…'),
* })
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await claimFailedDeposit(walletClient, {
* client: clientL2,
* depositHash: <L2_HASH_OF_FAILED_DEPOSIT>,
* })
*/
export async function claimFailedDeposit<
chain extends Chain | undefined,
account extends Account | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
chainL2 extends ChainEIP712 | undefined = ChainEIP712 | undefined,
accountL2 extends Account | undefined = Account | undefined,
_derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,
>(
client: Client<Transport, chain, account>,
parameters: ClaimFailedDepositParameters<
chain,
account,
chainOverride,
chainL2,
accountL2
>,
): Promise<ClaimFailedDepositReturnType> {
const {
account: account_ = client.account,
chain: chain_ = client.chain,
client: l2Client,
depositHash,
...rest
} = parameters
const account = account_ ? parseAccount(account_) : client.account
if (!account)
throw new AccountNotFoundError({
docsPath: '/docs/actions/wallet/sendTransaction',
})
if (!l2Client.chain) throw new ClientChainNotConfiguredError()
const receipt = <ZksyncTransactionReceipt>(
await getTransactionReceipt(l2Client, { hash: depositHash })
)
const successL2ToL1LogIndex = receipt.l2ToL1Logs.findIndex(
(l2ToL1log) =>
isAddressEqual(<Hex>l2ToL1log.sender, bootloaderFormalAddress) &&
l2ToL1log.key === depositHash,
)
const successL2ToL1Log = receipt.l2ToL1Logs[successL2ToL1LogIndex]
if (successL2ToL1Log?.value !== zeroHash)
throw new CannotClaimSuccessfulDepositError({ hash: depositHash })
const tx = await getTransaction(l2Client, { hash: depositHash })
// Undo the aliasing, since the Mailbox contract set it as for contract address.
const l1BridgeAddress = undoL1ToL2Alias(receipt.from)
const l2BridgeAddress = receipt.to
if (!l2BridgeAddress) throw new L2BridgeNotFoundError()
const l1NativeTokenVault = (await getBridgeAddresses(client, l2Client))
.l1NativeTokenVault
let depositSender: Hex
let assetId: Hex
let assetData: Hex
try {
const { args } = decodeFunctionData({
abi: parseAbi([
'function finalizeDeposit(address _l1Sender, address _l2Receiver, address _l1Token, uint256 _amount, bytes _data)',
]),
data: tx.input,
})
assetData = encodeAbiParameters(
[{ type: 'uint256' }, { type: 'address' }, { type: 'address' }],
[args[3], args[1], args[2]],
)
assetId = await readContract(client, {
address: l1NativeTokenVault,
abi: parseAbi(['function assetId(address token) view returns (bytes32)']),
functionName: 'assetId',
args: [args[2]],
})
depositSender = args[0]
if (assetId === zeroHash)
throw new Error(`Token ${args[2]} not registered in NTV`)
} catch (_e) {
const { args } = decodeFunctionData({
abi: parseAbi([
'function finalizeDeposit(uint256 _chainId, bytes32 _assetId, bytes _transferData)',
]),
data: tx.input,
})
assetId = args[1]
const transferData = args[2]
const l1TokenAddress = await readContract(client, {
address: l1NativeTokenVault,
abi: parseAbi([
'function tokenAddress(bytes32 assetId) view returns (address)',
]),
functionName: 'tokenAddress',
args: [assetId],
})
const transferDataDecoded = decodeAbiParameters(
[
{ type: 'address' },
{ type: 'address' },
{ type: 'address' },
{ type: 'uint256' },
{ type: 'bytes' },
],
transferData,
)
assetData = encodeAbiParameters(
[{ type: 'uint256' }, { type: 'address' }, { type: 'address' }],
[transferDataDecoded[3], transferDataDecoded[1], l1TokenAddress],
)
depositSender = transferDataDecoded[0]
}
const proof = await getLogProof(l2Client, {
txHash: depositHash,
index: successL2ToL1LogIndex,
})
if (!proof)
throw new LogProofNotFoundError({
hash: depositHash,
index: successL2ToL1LogIndex,
})
const data = encodeFunctionData({
abi: parseAbi([
'function bridgeRecoverFailedTransfer(uint256 _chainId, address _depositSender, bytes32 _assetId, bytes _assetData, bytes32 _l2TxHash, uint256 _l2BatchNumber, uint256 _l2MessageIndex, uint16 _l2TxNumberInBatch, bytes32[] _merkleProof)',
]),
functionName: 'bridgeRecoverFailedTransfer',
args: [
BigInt(l2Client.chain.id),
depositSender,
assetId,
assetData,
depositHash,
receipt.l1BatchNumber!,
BigInt(proof.id),
Number(receipt.l1BatchTxIndex),
proof.proof,
],
})
return await sendTransaction(client, {
chain: chain_,
account,
to: l1BridgeAddress,
data,
...rest,
} as SendTransactionParameters)
}
async function getBridgeAddresses<
chain extends Chain | undefined,
chainL2 extends ChainEIP712 | undefined,
>(
client: Client<Transport, chain>,
l2Client: Client<Transport, chainL2>,
): Promise<
BridgeContractAddresses & {
l1Nullifier: Address
l1NativeTokenVault: Address
}
> {
const addresses = await getDefaultBridgeAddresses(l2Client)
let l1Nullifier = addresses.l1Nullifier
let l1NativeTokenVault = addresses.l1NativeTokenVault
if (!l1Nullifier)
l1Nullifier = await readContract(client, {
address: addresses.sharedL1,
abi: parseAbi(['function L1_NULLIFIER() view returns (address)']),
functionName: 'L1_NULLIFIER',
args: [],
})
if (!l1NativeTokenVault)
l1NativeTokenVault = await readContract(client, {
address: addresses.sharedL1,
abi: parseAbi(['function nativeTokenVault() view returns (address)']),
functionName: 'nativeTokenVault',
args: [],
})
return {
...addresses,
l1Nullifier,
l1NativeTokenVault,
}
}

112
node_modules/viem/zksync/actions/deployContract.ts generated vendored Normal file
View File

@@ -0,0 +1,112 @@
import type { Abi } from 'abitype'
import type { Account } from '../../accounts/types.js'
import type { DeployContractParameters as DeployContractParameters_ } from '../../actions/wallet/deployContract.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { ErrorType } from '../../errors/utils.js'
import type { ContractConstructorArgs } from '../../types/contract.js'
import type { Hash, Hex } from '../../types/misc.js'
import {
contract2FactoryAddress,
contractDeployerAddress,
} from '../constants/address.js'
import type { ChainEIP712 } from '../types/chain.js'
import type { ContractDeploymentType } from '../types/contract.js'
import {
type EncodeDeployDataErrorType,
encodeDeployData,
} from '../utils/abi/encodeDeployData.js'
import {
type SendEip712TransactionErrorType,
type SendEip712TransactionParameters,
type SendEip712TransactionReturnType,
sendEip712Transaction,
} from './sendEip712Transaction.js'
export type DeployContractParameters<
abi extends Abi | readonly unknown[] = Abi,
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends ChainEIP712 | undefined = ChainEIP712 | undefined,
allArgs = ContractConstructorArgs<abi>,
> = DeployContractParameters_<abi, chain, account, chainOverride, allArgs> & {
deploymentType?: ContractDeploymentType | undefined
factoryDeps?: Hex[] | undefined
salt?: Hash | undefined
}
export type DeployContractReturnType = SendEip712TransactionReturnType
export type DeployContractErrorType =
| EncodeDeployDataErrorType
| SendEip712TransactionErrorType
| ErrorType
/**
* Deploys a contract to the network, given bytecode and constructor arguments using EIP712 transaction.
*
* - Docs: https://viem.sh/docs/contract/deployContract
*
* @param walletClient - Client to use
* @param parameters - {@link DeployContractParameters}
* @returns The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link DeployContractReturnType}
*
* @example
* import { createWalletClient, custom } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { deployContract } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: zksync,
* transport: custom(provider),
* })
* const hash = await deployContract(client, {
* abi: [],
* account: '0x…,
* deploymentType: 'create',
* bytecode: '0x608060405260405161083e38038061083e833981016040819052610...',
* factoryDeps: ['0x608060405260405161083e38038061083e833981016040819052610...'],
* gasPerPubdata: 50000n
* })
*/
export function deployContract<
const abi extends Abi | readonly unknown[],
chain extends ChainEIP712 | undefined,
account extends Account | undefined,
chainOverride extends ChainEIP712 | undefined,
>(
walletClient: Client<Transport, chain, account>,
parameters: DeployContractParameters<abi, chain, account, chainOverride>,
): Promise<DeployContractReturnType> {
const { abi, args, bytecode, deploymentType, salt, ...request } =
parameters as DeployContractParameters
const data = encodeDeployData({
abi,
args,
bytecode,
deploymentType,
salt,
})
// Add the bytecode to the factoryDeps if it's not already there
request.factoryDeps = request.factoryDeps || []
if (!request.factoryDeps.includes(bytecode))
request.factoryDeps.push(bytecode)
return sendEip712Transaction(walletClient, {
...request,
data,
to:
deploymentType === 'create2' || deploymentType === 'create2Account'
? contract2FactoryAddress
: contractDeployerAddress,
} as unknown as SendEip712TransactionParameters<
chain,
account,
chainOverride
>)
}

962
node_modules/viem/zksync/actions/deposit.ts generated vendored Normal file
View File

@@ -0,0 +1,962 @@
import { type Address, parseAbi } from 'abitype'
import type { Account } from '../../accounts/types.js'
import {
type EstimateGasParameters,
estimateGas,
} from '../../actions/public/estimateGas.js'
import { readContract } from '../../actions/public/readContract.js'
import { waitForTransactionReceipt } from '../../actions/public/waitForTransactionReceipt.js'
import {
type SendTransactionErrorType,
type SendTransactionParameters,
type SendTransactionReturnType,
sendTransaction,
} from '../../actions/wallet/sendTransaction.js'
import {
type WriteContractParameters,
writeContract,
} from '../../actions/wallet/writeContract.js'
import type { Client } from '../../clients/createClient.js'
import { publicActions } from '../../clients/decorators/public.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { erc20Abi } from '../../constants/abis.js'
import { zeroAddress } from '../../constants/address.js'
import { zeroHash } from '../../constants/bytes.js'
import { AccountNotFoundError } from '../../errors/account.js'
import { ClientChainNotConfiguredError } from '../../errors/chain.js'
import type { GetAccountParameter } from '../../types/account.js'
import type {
Chain,
DeriveChain,
GetChainParameter,
} from '../../types/chain.js'
import type { Hex } from '../../types/misc.js'
import type { UnionEvaluate, UnionOmit } from '../../types/utils.js'
import {
concatHex,
encodeAbiParameters,
encodeFunctionData,
type FormattedTransactionRequest,
isAddressEqual,
keccak256,
parseAccount,
} from '../../utils/index.js'
import { bridgehubAbi } from '../constants/abis.js'
import {
ethAddressInContracts,
l2NativeTokenVaultAddress,
legacyEthAddress,
} from '../constants/address.js'
import { requiredL1ToL2GasPerPubdataLimit } from '../constants/number.js'
import {
BaseFeeHigherThanValueError,
type BaseFeeHigherThanValueErrorType,
} from '../errors/bridge.js'
import type { ChainEIP712 } from '../types/chain.js'
import type { BridgeContractAddresses } from '../types/contract.js'
import { applyL1ToL2Alias } from '../utils/bridge/applyL1ToL2Alias.js'
import { estimateGasL1ToL2 } from './estimateGasL1ToL2.js'
import { getBridgehubContractAddress } from './getBridgehubContractAddress.js'
import { getDefaultBridgeAddresses } from './getDefaultBridgeAddresses.js'
import { getL1Allowance } from './getL1Allowance.js'
export type DepositParameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
chainL2 extends ChainEIP712 | undefined = ChainEIP712 | undefined,
accountL2 extends Account | undefined = Account | undefined,
_derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,
> = UnionEvaluate<
UnionOmit<FormattedTransactionRequest<_derivedChain>, 'data' | 'to' | 'from'>
> &
Partial<GetChainParameter<chain, chainOverride>> &
Partial<GetAccountParameter<account>> & {
/** L2 client. */
client: Client<Transport, chainL2, accountL2>
/** The address of the token to deposit. */
token: Address
/** The amount of the token to deposit. */
amount: bigint
/** The address that will receive the deposited tokens on L2.
Defaults to the sender address.*/
to?: Address | undefined
/** (currently not used) The tip the operator will receive on top of
the base cost of the transaction. */
operatorTip?: bigint | undefined
/** Maximum amount of L2 gas that transaction can consume during execution on L2. */
l2GasLimit?: bigint | undefined
/** The L2 gas price for each published L1 calldata byte. */
gasPerPubdataByte?: bigint | undefined
/** The address on L2 that will receive the refund for the transaction.
If the transaction fails, it will also be the address to receive `amount`. */
refundRecipient?: Address | undefined
/** The address of the bridge contract to be used.
Defaults to the default ZKsync L1 shared bridge. */
bridgeAddress?: Address | undefined
/** Additional data that can be sent to a bridge. */
customBridgeData?: Hex | undefined
/** Whether token approval should be performed under the hood.
Set this flag to true (or provide transaction overrides) if the bridge does
not have sufficient allowance. The approval transaction is executed only if
the bridge lacks sufficient allowance; otherwise, it is skipped. */
approveToken?:
| boolean
| UnionEvaluate<
UnionOmit<
FormattedTransactionRequest<_derivedChain>,
'data' | 'to' | 'from'
>
>
| undefined
/** Whether base token approval should be performed under the hood.
Set this flag to true (or provide transaction overrides) if the bridge does
not have sufficient allowance. The approval transaction is executed only if
the bridge lacks sufficient allowance; otherwise, it is skipped. */
approveBaseToken?:
| boolean
| UnionEvaluate<
UnionOmit<
FormattedTransactionRequest<_derivedChain>,
'data' | 'to' | 'from'
>
>
| undefined
}
export type DepositReturnType = SendTransactionReturnType
export type DepositErrorType =
| SendTransactionErrorType
| BaseFeeHigherThanValueErrorType
/**
* Transfers the specified token from the associated account on the L1 network to the target account on the L2 network.
* The token can be either ETH or any ERC20 token. For ERC20 tokens, enough approved tokens must be associated with
* the specified L1 bridge (default one or the one defined in `bridgeAddress`).
* In this case, depending on is the chain ETH-based or not `approveToken` or `approveBaseToken`
* can be enabled to perform token approval. If there are already enough approved tokens for the L1 bridge,
* token approval will be skipped.
*
* @param client - Client to use
* @param parameters - {@link DepositParameters}
* @returns hash - The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link DepositReturnType}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync, mainnet } from 'viem/chains'
* import { deposit, legacyEthAddress, publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const account = privateKeyToAccount('0x…')
*
* const hash = await deposit(client, {
* client: clientL2,
* account,
* token: legacyEthAddress,
* to: account.address,
* amount: 1_000_000_000_000_000_000n,
* refundRecipient: account.address,
* })
*
* @example Account Hoisting
* import { createPublicClient, createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync, mainnet } from 'viem/chains'
* import { legacyEthAddress, publicActionsL2 } from 'viem/zksync'
*
* const walletClient = createWalletClient({
* chain: mainnet,
* transport: http(),
* account: privateKeyToAccount('0x…'),
* })
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await deposit(walletClient, {
* client: clientL2,
* token: legacyEthAddress,
* to: walletClient.account.address,
* amount: 1_000_000_000_000_000_000n,
* refundRecipient: walletClient.account.address,
* })
*/
export async function deposit<
chain extends Chain | undefined,
account extends Account | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
chainL2 extends ChainEIP712 | undefined = ChainEIP712 | undefined,
accountL2 extends Account | undefined = Account | undefined,
_derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,
>(
client: Client<Transport, chain, account>,
parameters: DepositParameters<
chain,
account,
chainOverride,
chainL2,
accountL2
>,
): Promise<DepositReturnType> {
let {
account: account_ = client.account,
chain: chain_ = client.chain,
client: l2Client,
token,
amount,
approveToken,
approveBaseToken,
gas,
} = parameters
const account = account_ ? parseAccount(account_) : client.account
if (!account)
throw new AccountNotFoundError({
docsPath: '/docs/actions/wallet/sendTransaction',
})
if (!l2Client.chain) throw new ClientChainNotConfiguredError()
if (isAddressEqual(token, legacyEthAddress)) token = ethAddressInContracts
const bridgeAddresses = await getBridgeAddresses(client, l2Client)
const bridgehub = await getBridgehubContractAddress(l2Client)
const baseToken = await readContract(client, {
address: bridgehub,
abi: bridgehubAbi,
functionName: 'baseToken',
args: [BigInt(l2Client.chain.id)],
})
const { mintValue, tx } = await getL1DepositTx(
client,
account,
{ ...parameters, token },
bridgeAddresses,
bridgehub,
baseToken,
)
await approveTokens(
client,
chain_,
tx.bridgeAddress,
baseToken,
mintValue,
account,
token,
amount,
approveToken,
approveBaseToken,
)
if (!gas) {
const baseGasLimit = await estimateGas(client, {
account: account.address,
to: bridgehub,
value: tx.value,
data: tx.data,
} as EstimateGasParameters)
gas = scaleGasLimit(baseGasLimit)
}
return await sendTransaction(client, {
chain: chain_,
account,
gas,
...tx,
} as SendTransactionParameters)
}
async function getL1DepositTx<
chain extends Chain | undefined,
account extends Account | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
chainL2 extends ChainEIP712 | undefined = ChainEIP712 | undefined,
accountL2 extends Account | undefined = Account | undefined,
_derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,
>(
client: Client<Transport, chain, account>,
account: Account,
parameters: DepositParameters<
chain,
account,
chainOverride,
chainL2,
accountL2,
_derivedChain
>,
bridgeAddresses: BridgeContractAddresses & {
l1Nullifier: Address
l1NativeTokenVault: Address
},
bridgehub: Address,
baseToken: Address,
) {
let {
account: _account,
chain: _chain,
client: l2Client,
token,
amount,
to,
operatorTip = 0n,
l2GasLimit,
gasPerPubdataByte = requiredL1ToL2GasPerPubdataLimit,
refundRecipient = zeroAddress,
bridgeAddress,
customBridgeData,
value,
gasPrice,
maxFeePerGas,
maxPriorityFeePerGas,
approveToken: _approveToken,
approveBaseToken: _approveBaseToken,
...rest
} = parameters
if (!l2Client.chain) throw new ClientChainNotConfiguredError()
to ??= account.address
let gasPriceForEstimation = maxFeePerGas || gasPrice
if (!gasPriceForEstimation) {
const estimatedFee = await getFeePrice(client)
gasPriceForEstimation = estimatedFee.maxFeePerGas
maxFeePerGas = estimatedFee.maxFeePerGas
maxPriorityFeePerGas ??= estimatedFee.maxPriorityFeePerGas
}
const { l2GasLimit_, baseCost } = await getL2BridgeTxFeeParams(
client,
l2Client,
bridgehub,
gasPriceForEstimation,
account.address,
token,
amount,
to,
gasPerPubdataByte,
baseToken,
l2GasLimit,
bridgeAddress,
customBridgeData,
)
l2GasLimit = l2GasLimit_
let mintValue: bigint
let data: Hex
const isETHBasedChain = isAddressEqual(baseToken, ethAddressInContracts)
if (
(isETHBasedChain && isAddressEqual(token, ethAddressInContracts)) || // ETH on ETH-based chain
isAddressEqual(token, baseToken) // base token on custom chain
) {
// Deposit base token
mintValue = baseCost + operatorTip + amount
let providedValue = isETHBasedChain ? value : mintValue
if (!providedValue || providedValue === 0n) providedValue = mintValue
if (baseCost > providedValue)
throw new BaseFeeHigherThanValueError(baseCost, providedValue)
value = isETHBasedChain ? providedValue : 0n
bridgeAddress = bridgeAddresses.sharedL1 // required for approval of base token on custom chain
data = encodeFunctionData({
abi: bridgehubAbi,
functionName: 'requestL2TransactionDirect',
args: [
{
chainId: BigInt(l2Client.chain.id),
mintValue: providedValue,
l2Contract: to,
l2Value: amount,
l2Calldata: '0x',
l2GasLimit,
l2GasPerPubdataByteLimit: gasPerPubdataByte,
factoryDeps: [],
refundRecipient,
},
],
})
} else if (isAddressEqual(baseToken, ethAddressInContracts)) {
// Deposit token on ETH-based chain
mintValue = baseCost + BigInt(operatorTip)
value = mintValue
if (baseCost > mintValue)
throw new BaseFeeHigherThanValueError(baseCost, mintValue)
bridgeAddress ??= bridgeAddresses.sharedL1
data = encodeFunctionData({
abi: bridgehubAbi,
functionName: 'requestL2TransactionTwoBridges',
args: [
{
chainId: BigInt(l2Client.chain.id),
mintValue,
l2Value: 0n,
l2GasLimit,
l2GasPerPubdataByteLimit: gasPerPubdataByte,
refundRecipient,
secondBridgeAddress: bridgeAddress,
secondBridgeValue: 0n,
secondBridgeCalldata: await getSecondBridgeCalldata(
client,
bridgeAddresses.l1NativeTokenVault,
token,
amount,
to,
),
},
],
})
} else if (isAddressEqual(token, ethAddressInContracts)) {
// Deposit ETH on custom chain
mintValue = baseCost + operatorTip
value = amount
if (baseCost > mintValue)
throw new BaseFeeHigherThanValueError(baseCost, mintValue)
bridgeAddress = bridgeAddresses.sharedL1
data = encodeFunctionData({
abi: bridgehubAbi,
functionName: 'requestL2TransactionTwoBridges',
args: [
{
chainId: BigInt(l2Client.chain.id),
mintValue,
l2Value: 0n,
l2GasLimit,
l2GasPerPubdataByteLimit: gasPerPubdataByte,
refundRecipient,
secondBridgeAddress: bridgeAddress,
secondBridgeValue: amount,
secondBridgeCalldata: await getSecondBridgeCalldata(
client,
bridgeAddresses.l1NativeTokenVault,
ethAddressInContracts,
amount,
to,
),
},
],
})
} else {
// Deposit token on custom chain
mintValue = baseCost + operatorTip
value ??= 0n
if (baseCost > mintValue)
throw new BaseFeeHigherThanValueError(baseCost, mintValue)
bridgeAddress ??= bridgeAddresses.sharedL1
data = encodeFunctionData({
abi: bridgehubAbi,
functionName: 'requestL2TransactionTwoBridges',
args: [
{
chainId: BigInt(l2Client.chain.id),
mintValue,
l2Value: 0n,
l2GasLimit,
l2GasPerPubdataByteLimit: gasPerPubdataByte,
refundRecipient,
secondBridgeAddress: bridgeAddress,
secondBridgeValue: 0n,
secondBridgeCalldata: await getSecondBridgeCalldata(
client,
bridgeAddresses.l1NativeTokenVault,
token,
amount,
to,
),
},
],
})
}
return {
mintValue,
tx: {
bridgeAddress,
to: bridgehub,
data,
value,
gasPrice,
maxFeePerGas,
maxPriorityFeePerGas,
...rest,
},
}
}
async function approveTokens<
chain extends Chain | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
_derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,
>(
client: Client<Transport, chain>,
chain: Chain | null | undefined,
bridgeAddress: Address,
baseToken: Address,
mintValue: bigint,
account: Account,
token: Address,
amount: bigint,
approveToken?:
| boolean
| UnionEvaluate<
UnionOmit<
FormattedTransactionRequest<_derivedChain>,
'data' | 'to' | 'from'
>
>
| undefined,
approveBaseToken?:
| boolean
| UnionEvaluate<
UnionOmit<
FormattedTransactionRequest<_derivedChain>,
'data' | 'to' | 'from'
>
>
| undefined,
) {
if (isAddressEqual(baseToken, ethAddressInContracts)) {
// Deposit token on ETH-based chain
if (approveToken) {
const overrides = typeof approveToken === 'boolean' ? {} : approveToken
const allowance = await getL1Allowance(client, {
token,
bridgeAddress,
account,
})
if (allowance < amount) {
const hash = await writeContract(client, {
chain,
account,
address: token,
abi: erc20Abi,
functionName: 'approve',
args: [bridgeAddress, amount],
...overrides,
} satisfies WriteContractParameters as any)
await waitForTransactionReceipt(client, { hash })
}
}
return
}
if (isAddressEqual(token, ethAddressInContracts)) {
// Deposit ETH on custom chain
if (approveBaseToken) {
const overrides = typeof approveToken === 'boolean' ? {} : approveToken
const allowance = await getL1Allowance(client, {
token: baseToken,
bridgeAddress,
account,
})
if (allowance < mintValue) {
const hash = await writeContract(client, {
chain,
account,
address: baseToken,
abi: erc20Abi,
functionName: 'approve',
args: [bridgeAddress, mintValue],
...overrides,
} satisfies WriteContractParameters as any)
await waitForTransactionReceipt(client, { hash })
}
return
}
}
if (isAddressEqual(token, baseToken)) {
// Deposit base token on custom chain
if (approveToken || approveBaseToken) {
const overrides =
typeof approveToken === 'boolean'
? {}
: (approveToken ?? typeof approveBaseToken === 'boolean')
? {}
: approveBaseToken
const allowance = await getL1Allowance(client, {
token: baseToken,
bridgeAddress,
account,
})
if (allowance < mintValue) {
const hash = await writeContract(client, {
chain,
account,
address: baseToken,
abi: erc20Abi,
functionName: 'approve',
args: [bridgeAddress, mintValue],
...overrides,
} satisfies WriteContractParameters as any)
await waitForTransactionReceipt(client, { hash })
}
}
return
}
// Deposit token on custom chain
if (approveBaseToken) {
const overrides = typeof approveToken === 'boolean' ? {} : approveToken
const allowance = await getL1Allowance(client, {
token: baseToken,
bridgeAddress,
account,
})
if (allowance < mintValue) {
const hash = await writeContract(client, {
chain,
account,
address: baseToken,
abi: erc20Abi,
functionName: 'approve',
args: [bridgeAddress, mintValue],
...overrides,
} satisfies WriteContractParameters as any)
await waitForTransactionReceipt(client, { hash })
}
}
if (approveToken) {
const overrides = typeof approveToken === 'boolean' ? {} : approveToken
const allowance = await getL1Allowance(client, {
token,
bridgeAddress,
account,
})
if (allowance < amount) {
const hash = await writeContract(client, {
chain,
account,
address: token,
abi: erc20Abi,
functionName: 'approve',
args: [bridgeAddress, amount],
...overrides,
} satisfies WriteContractParameters as any)
await waitForTransactionReceipt(client, { hash })
}
}
}
async function getL2BridgeTxFeeParams<
chain extends Chain | undefined,
chainL2 extends ChainEIP712 | undefined,
>(
client: Client<Transport, chain>,
l2Client: Client<Transport, chainL2>,
bridgehub: Address,
gasPrice: bigint,
from: Address,
token: Address,
amount: bigint,
to: Address,
gasPerPubdataByte: bigint,
baseToken: Address,
l2GasLimit?: bigint | undefined,
bridgeAddress?: Address | undefined,
customBridgeData?: Hex | undefined,
) {
if (!l2Client.chain) throw new ClientChainNotConfiguredError()
let l2GasLimit_ = l2GasLimit
if (!l2GasLimit_)
l2GasLimit_ = bridgeAddress
? await getL2GasLimitFromCustomBridge(
client,
l2Client,
from,
token,
amount,
to,
gasPerPubdataByte,
bridgeAddress,
customBridgeData,
)
: await getL2GasLimitFromDefaultBridge(
client,
l2Client,
from,
token,
amount,
to,
gasPerPubdataByte,
baseToken,
)
const baseCost = await readContract(client, {
address: bridgehub,
abi: bridgehubAbi,
functionName: 'l2TransactionBaseCost',
args: [BigInt(l2Client.chain.id), gasPrice, l2GasLimit_, gasPerPubdataByte],
})
return { l2GasLimit_, baseCost }
}
async function getL2GasLimitFromDefaultBridge<
chain extends Chain | undefined,
chainL2 extends ChainEIP712 | undefined,
>(
client: Client<Transport, chain>,
l2Client: Client<Transport, chainL2>,
from: Address,
token: Address,
amount: bigint,
to: Address,
gasPerPubdataByte: bigint,
baseToken: Address,
) {
if (isAddressEqual(token, baseToken)) {
return await estimateGasL1ToL2(l2Client, {
chain: l2Client.chain,
account: from,
from,
to,
value: amount,
data: '0x',
gasPerPubdata: gasPerPubdataByte,
})
}
const value = 0n
const bridgeAddresses = await getDefaultBridgeAddresses(l2Client)
const l1BridgeAddress = bridgeAddresses.sharedL1
const l2BridgeAddress = bridgeAddresses.sharedL2
const bridgeData = await encodeDefaultBridgeData(client, token)
const calldata = encodeFunctionData({
abi: parseAbi([
'function finalizeDeposit(address _l1Sender, address _l2Receiver, address _l1Token, uint256 _amount, bytes _data)',
]),
functionName: 'finalizeDeposit',
args: [
from,
to,
isAddressEqual(token, legacyEthAddress) ? ethAddressInContracts : token,
amount,
bridgeData,
],
})
return await estimateGasL1ToL2(l2Client, {
chain: l2Client.chain,
account: applyL1ToL2Alias(l1BridgeAddress),
to: l2BridgeAddress,
data: calldata,
gasPerPubdata: gasPerPubdataByte,
value,
})
}
async function getL2GasLimitFromCustomBridge<
chain extends Chain | undefined,
chainL2 extends ChainEIP712 | undefined,
>(
client: Client<Transport, chain>,
l2Client: Client<Transport, chainL2>,
from: Address,
token: Address,
amount: bigint,
to: Address,
gasPerPubdataByte: bigint,
bridgeAddress: Address,
customBridgeData?: Hex,
) {
let customBridgeData_ = customBridgeData
if (!customBridgeData_ || customBridgeData_ === '0x')
customBridgeData_ = await encodeDefaultBridgeData(client, token)
const l2BridgeAddress = await readContract(client, {
address: token,
abi: parseAbi([
'function l2BridgeAddress(uint256 _chainId) view returns (address)',
]),
functionName: 'l2BridgeAddress',
args: [BigInt(l2Client.chain!.id)],
})
const calldata = encodeFunctionData({
abi: parseAbi([
'function finalizeDeposit(address _l1Sender, address _l2Receiver, address _l1Token, uint256 _amount, bytes _data)',
]),
functionName: 'finalizeDeposit',
args: [from, to, token, amount, customBridgeData_],
})
return await estimateGasL1ToL2(l2Client, {
chain: l2Client.chain,
account: from,
from: applyL1ToL2Alias(bridgeAddress),
to: l2BridgeAddress,
data: calldata,
gasPerPubdata: gasPerPubdataByte,
})
}
async function encodeDefaultBridgeData<chain extends Chain | undefined>(
client: Client<Transport, chain>,
token: Address,
) {
let token_ = token
if (isAddressEqual(token, legacyEthAddress)) token_ = ethAddressInContracts
let name = 'Ether'
let symbol = 'ETH'
let decimals = 18n
if (!isAddressEqual(token_, ethAddressInContracts)) {
name = await readContract(client, {
address: token_,
abi: erc20Abi,
functionName: 'name',
args: [],
})
symbol = await readContract(client, {
address: token_,
abi: erc20Abi,
functionName: 'symbol',
args: [],
})
decimals = BigInt(
await readContract(client, {
address: token_,
abi: erc20Abi,
functionName: 'decimals',
args: [],
}),
)
}
const nameBytes = encodeAbiParameters([{ type: 'string' }], [name])
const symbolBytes = encodeAbiParameters([{ type: 'string' }], [symbol])
const decimalsBytes = encodeAbiParameters([{ type: 'uint256' }], [decimals])
return encodeAbiParameters(
[{ type: 'bytes' }, { type: 'bytes' }, { type: 'bytes' }],
[nameBytes, symbolBytes, decimalsBytes],
)
}
async function getSecondBridgeCalldata<chain extends Chain | undefined>(
client: Client<Transport, chain>,
l1NativeTokenVault: Address,
token: Address,
amount: bigint,
to: Address,
): Promise<Hex> {
let assetId: Hex
let token_ = token
if (isAddressEqual(token, legacyEthAddress)) token_ = ethAddressInContracts
const assetIdFromNTV = await readContract(client, {
address: l1NativeTokenVault,
abi: parseAbi(['function assetId(address token) view returns (bytes32)']),
functionName: 'assetId',
args: [token_],
})
if (assetIdFromNTV && assetIdFromNTV !== zeroHash) assetId = assetIdFromNTV
else {
// Okay, the token have not been registered within the Native token vault.
// There are two cases when it is possible:
// - The token is native to L1 (it may or may not be bridged), but it has not been
// registered within NTV after the Gateway upgrade. We assume that this is not the case
// as the SDK is expected to work only after the full migration is done.
// - The token is native to the current chain and it has never been bridged.
if (!client.chain) throw new ClientChainNotConfiguredError()
assetId = keccak256(
encodeAbiParameters(
[{ type: 'uint256' }, { type: 'address' }, { type: 'address' }],
[BigInt(client.chain.id), l2NativeTokenVaultAddress, token_],
),
)
}
const ntvData = encodeAbiParameters(
[{ type: 'uint256' }, { type: 'address' }, { type: 'address' }],
[BigInt(amount), to, token_],
)
const data = encodeAbiParameters(
[{ type: 'bytes32' }, { type: 'bytes' }],
[assetId, ntvData],
)
return concatHex(['0x01', data])
}
async function getBridgeAddresses<
chain extends Chain | undefined,
chainL2 extends ChainEIP712 | undefined,
>(
client: Client<Transport, chain>,
l2Client: Client<Transport, chainL2>,
): Promise<
BridgeContractAddresses & {
l1Nullifier: Address
l1NativeTokenVault: Address
}
> {
const addresses = await getDefaultBridgeAddresses(l2Client)
let l1Nullifier = addresses.l1Nullifier
let l1NativeTokenVault = addresses.l1NativeTokenVault
if (!l1Nullifier)
l1Nullifier = await readContract(client, {
address: addresses.sharedL1,
abi: parseAbi(['function L1_NULLIFIER() view returns (address)']),
functionName: 'L1_NULLIFIER',
args: [],
})
if (!l1NativeTokenVault)
l1NativeTokenVault = await readContract(client, {
address: addresses.sharedL1,
abi: parseAbi(['function nativeTokenVault() view returns (address)']),
functionName: 'nativeTokenVault',
args: [],
})
return {
...addresses,
l1Nullifier,
l1NativeTokenVault,
}
}
function scaleGasLimit(gasLimit: bigint): bigint {
return (gasLimit * BigInt(12)) / BigInt(10)
}
async function getFeePrice<chain extends Chain | undefined>(
client: Client<Transport, chain>,
) {
const client_ = client.extend(publicActions)
const block = await client_.getBlock()
const baseFee =
typeof block.baseFeePerGas !== 'bigint'
? await client_.getGasPrice()
: block.baseFeePerGas
const maxPriorityFeePerGas = await client_.estimateMaxPriorityFeePerGas()
return {
maxFeePerGas: (baseFee * 3n) / 2n + maxPriorityFeePerGas,
maxPriorityFeePerGas: maxPriorityFeePerGas,
}
}

49
node_modules/viem/zksync/actions/estimateFee.ts generated vendored Normal file
View File

@@ -0,0 +1,49 @@
import { parseAccount } from '../../accounts/utils/parseAccount.js'
import type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import { hexToBigInt } from '../../utils/encoding/fromHex.js'
import type { ChainEIP712 } from '../types/chain.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
import type { ZksyncFee } from '../types/fee.js'
export type EstimateFeeParameters<
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends ChainEIP712 | undefined = ChainEIP712 | undefined,
> = SendTransactionParameters<chain, account, chainOverride>
export type EstimateFeeReturnType = ZksyncFee
/* @deprecated Use `eth_gasPrice` for `maxFeePerGas`, `eth_estimateGas` to get the `gasLimit`, set `maxPriorityFeePerGas` to `0`, and use `zks_gasPerPubdata` for `gasPerPubdataLimit` instead. */
export async function estimateFee<
chain extends ChainEIP712 | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
parameters: EstimateFeeParameters<chain, account>,
): Promise<EstimateFeeReturnType> {
const { account: account_, ...request } = parameters
const account = account_ ? parseAccount(account_) : client.account
const formatters = client.chain?.formatters
const formatted = formatters?.transactionRequest?.format(
{
...request,
from: account?.address,
},
'estimateFee',
)
const result = await client.request({
method: 'zks_estimateFee',
params: [formatted],
})
return {
gasLimit: hexToBigInt(result.gas_limit),
gasPerPubdataLimit: hexToBigInt(result.gas_per_pubdata_limit),
maxPriorityFeePerGas: hexToBigInt(result.max_priority_fee_per_gas),
maxFeePerGas: hexToBigInt(result.max_fee_per_gas),
}
}

41
node_modules/viem/zksync/actions/estimateGasL1ToL2.ts generated vendored Normal file
View File

@@ -0,0 +1,41 @@
import { parseAccount } from '../../accounts/utils/parseAccount.js'
import type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { ChainEIP712 } from '../types/chain.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type EstimateGasL1ToL2Parameters<
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
> = SendTransactionParameters<chain, account>
export type EstimateGasL1ToL2ReturnType = bigint
export async function estimateGasL1ToL2<
chain extends ChainEIP712 | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
parameters: EstimateGasL1ToL2Parameters<chain, account>,
): Promise<EstimateGasL1ToL2ReturnType> {
const { account: account_, ...request } = parameters
const account = account_ ? parseAccount(account_) : client.account
const formatters = client.chain?.formatters
const formatted = formatters?.transactionRequest?.format(
{
...request,
from: account?.address,
},
'estimateGasL1ToL2',
)
const result = await client.request({
method: 'zks_estimateGasL1ToL2',
params: [formatted],
})
return result
}

250
node_modules/viem/zksync/actions/finalizeWithdrawal.ts generated vendored Normal file
View File

@@ -0,0 +1,250 @@
import { type Address, parseAbi } from 'abitype'
import type { Account } from '../../accounts/types.js'
import { readContract } from '../../actions/public/readContract.js'
import {
type SendTransactionErrorType,
type SendTransactionParameters,
type SendTransactionRequest,
type SendTransactionReturnType,
sendTransaction,
} from '../../actions/wallet/sendTransaction.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { AccountNotFoundError } from '../../errors/account.js'
import {
ChainNotFoundError,
type ChainNotFoundErrorType,
} from '../../errors/chain.js'
import type { Chain } from '../../types/chain.js'
import type { Hex } from '../../types/misc.js'
import {
decodeAbiParameters,
encodeFunctionData,
parseAccount,
slice,
} from '../../utils/index.js'
import {
WithdrawalLogNotFoundError,
type WithdrawalLogNotFoundErrorType,
} from '../errors/bridge.js'
import type { ChainEIP712 } from '../types/chain.js'
import type { BridgeContractAddresses } from '../types/contract.js'
import { getWithdrawalL2ToL1Log } from '../utils/bridge/getWithdrawalL2ToL1Log.js'
import { getWithdrawalLog } from '../utils/bridge/getWithdrawalLog.js'
import { getDefaultBridgeAddresses } from './getDefaultBridgeAddresses.js'
import { getLogProof } from './getLogProof.js'
export type FinalizeWithdrawalParameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
chainL2 extends ChainEIP712 | undefined = ChainEIP712 | undefined,
accountL2 extends Account | undefined = Account | undefined,
request extends SendTransactionRequest<
chain,
chainOverride
> = SendTransactionRequest<chain, chainOverride>,
> = Omit<
SendTransactionParameters<chain, account, chainOverride, request>,
'value' | 'data' | 'to'
> & {
/** L2 client */
client: Client<Transport, chainL2, accountL2>
/** Hash of the L2 transaction where the withdrawal was initiated. */
hash: Hex
/** In case there were multiple withdrawals in one transaction, you may pass an index of the
withdrawal you want to finalize. */
index?: number | undefined
}
export type FinalizeWithdrawalReturnType = SendTransactionReturnType
export type FinalizeWithdrawalErrorType =
| SendTransactionErrorType
| WithdrawalLogNotFoundErrorType
| ChainNotFoundErrorType
/**
* Proves the inclusion of the `L2->L1` withdrawal message.
*
* @param client - Client to use
* @param parameters - {@link FinalizeWithdrawalParameters}
* @returns hash - The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link FinalizeWithdrawalReturnType}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { mainnet, zksync } from 'viem/chains'
* import { finalizeWithdrawal, publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await finalizeWithdrawal(client, {
* account: privateKeyToAccount('0x…'),
* client: clientL2,
* hash: '0x...',
* })
*
* @example Account Hoisting
* import { createPublicClient, createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { mainnet, zksync } from 'viem/chains'
* import { finalizeWithdrawal, publicActionsL2 } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: mainnet,
* transport: http(),
* })
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await finalizeWithdrawal(client, {
* client: clientL2,
* hash: '0x…',
* })
*/
export async function finalizeWithdrawal<
chain extends Chain | undefined,
account extends Account | undefined,
accountL2 extends Account | undefined,
const request extends SendTransactionRequest<chain, chainOverride>,
chainOverride extends Chain | undefined,
chainL2 extends ChainEIP712 | undefined,
>(
client: Client<Transport, chain, account>,
parameters: FinalizeWithdrawalParameters<
chain,
account,
chainOverride,
chainL2,
accountL2,
request
>,
): Promise<FinalizeWithdrawalReturnType> {
const {
account: account_ = client.account,
client: l2Client,
hash,
index = 0,
...rest
} = parameters
const account = account_ ? parseAccount(account_) : client.account
if (!account)
throw new AccountNotFoundError({
docsPath: '/docs/actions/wallet/sendTransaction',
})
if (!l2Client.chain) throw new ChainNotFoundError()
const finalizeWithdrawalParams = await getFinalizeWithdrawalParams(l2Client, {
hash,
index,
})
const l1Nullifier = (await getBridgeAddresses(client, l2Client)).l1Nullifier
const data = encodeFunctionData({
abi: parseAbi([
'function finalizeDeposit((uint256 chainId, uint256 l2BatchNumber, uint256 l2MessageIndex, address l2Sender, uint16 l2TxNumberInBatch, bytes message, bytes32[] merkleProof) _finalizeWithdrawalParams)',
]),
functionName: 'finalizeDeposit',
args: [
{
chainId: BigInt(l2Client.chain.id),
l2BatchNumber: finalizeWithdrawalParams.l1BatchNumber!,
l2MessageIndex: BigInt(finalizeWithdrawalParams.l2MessageIndex),
l2Sender: finalizeWithdrawalParams.sender,
l2TxNumberInBatch: Number(finalizeWithdrawalParams.l2TxNumberInBlock),
message: finalizeWithdrawalParams.message,
merkleProof: finalizeWithdrawalParams.proof,
},
],
})
return await sendTransaction(client, {
account,
to: l1Nullifier,
data,
...rest,
} as SendTransactionParameters)
}
async function getFinalizeWithdrawalParams<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: { hash: Hex; index: number },
) {
const { hash } = parameters
const { log, l1BatchTxId } = await getWithdrawalLog(client, parameters)
const { l2ToL1LogIndex } = await getWithdrawalL2ToL1Log(client, parameters)
const sender = slice(log.topics[1]!, 12) as Address
const proof = await getLogProof(client, {
txHash: hash,
index: l2ToL1LogIndex!,
})
if (!proof) {
throw new WithdrawalLogNotFoundError({ hash })
}
const [message] = decodeAbiParameters([{ type: 'bytes' }], log.data)
return {
l1BatchNumber: log.l1BatchNumber,
l2MessageIndex: proof.id,
l2TxNumberInBlock: l1BatchTxId,
message,
sender,
proof: proof.proof,
}
}
async function getBridgeAddresses<
chain extends Chain | undefined,
chainL2 extends ChainEIP712 | undefined,
>(
client: Client<Transport, chain>,
l2Client: Client<Transport, chainL2>,
): Promise<
BridgeContractAddresses & {
l1Nullifier: Address
l1NativeTokenVault: Address
}
> {
const addresses = await getDefaultBridgeAddresses(l2Client)
let l1Nullifier = addresses.l1Nullifier
let l1NativeTokenVault = addresses.l1NativeTokenVault
if (!l1Nullifier)
l1Nullifier = await readContract(client, {
address: addresses.sharedL1,
abi: parseAbi(['function L1_NULLIFIER() view returns (address)']),
functionName: 'L1_NULLIFIER',
args: [],
})
if (!l1NativeTokenVault)
l1NativeTokenVault = await readContract(client, {
address: addresses.sharedL1,
abi: parseAbi(['function nativeTokenVault() view returns (address)']),
functionName: 'nativeTokenVault',
args: [],
})
return {
...addresses,
l1Nullifier,
l1NativeTokenVault,
}
}

34
node_modules/viem/zksync/actions/getAllBalances.ts generated vendored Normal file
View File

@@ -0,0 +1,34 @@
import type { Address } from 'abitype'
import { parseAccount } from '../../accounts/utils/parseAccount.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account, GetAccountParameter } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import { hexToBigInt } from '../../utils/encoding/fromHex.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type GetAllBalancesParameters<
account extends Account | undefined = Account | undefined,
> = GetAccountParameter<account>
export type GetAllBalancesReturnType = { [key: Address]: bigint }
/* @deprecated This method has been removed from the node API. */
export async function getAllBalances<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
parameters: GetAllBalancesParameters<account>,
): Promise<GetAllBalancesReturnType> {
const { account: account_ } = parameters
const account = account_ ? parseAccount(account_) : client.account
const balances = await client.request({
method: 'zks_getAllAccountBalances',
params: [account!.address],
})
const convertedBalances: GetAllBalancesReturnType = {}
for (const token in balances)
(convertedBalances as any)[token] = hexToBigInt((balances as any)[token])
return convertedBalances
}

View File

@@ -0,0 +1,19 @@
import type { Address } from 'abitype'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type GetBaseTokenL1AddressReturnType = Address
/* @deprecated Use `getBridgeHubContractAddress` and call `baseToken(chainId)` instead. */
export async function getBaseTokenL1Address<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
): Promise<GetBaseTokenL1AddressReturnType> {
const result = await client.request({ method: 'zks_getBaseTokenL1Address' })
return result
}

27
node_modules/viem/zksync/actions/getBlockDetails.ts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import type {
ZksyncBlockDetails,
ZksyncNumberParameter,
} from '../types/block.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type GetBlockDetailsParameters = ZksyncNumberParameter
export type GetBlockDetailsReturnType = ZksyncBlockDetails
export async function getBlockDetails<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
parameters: GetBlockDetailsParameters,
): Promise<GetBlockDetailsReturnType> {
const result = await client.request({
method: 'zks_getBlockDetails',
params: [parameters.number],
})
return result
}

View File

@@ -0,0 +1,18 @@
import type { Address } from 'abitype'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type GetBridgehubContractAddressReturnType = Address
export async function getBridgehubContractAddress<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
): Promise<GetBridgehubContractAddressReturnType> {
const result = await client.request({ method: 'zks_getBridgehubContract' })
return result
}

View File

@@ -0,0 +1,25 @@
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import type { BridgeContractAddresses } from '../types/contract.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type GetDefaultBridgeAddressesReturnType = BridgeContractAddresses
export async function getDefaultBridgeAddresses<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
): Promise<GetDefaultBridgeAddressesReturnType> {
const addresses = await client.request({ method: 'zks_getBridgeContracts' })
return {
erc20L1: addresses.l1Erc20DefaultBridge,
sharedL1: addresses.l1SharedDefaultBridge,
sharedL2: addresses.l2SharedDefaultBridge,
l1Nullifier: addresses.l1Nullifier,
l1NativeTokenVault: addresses.l1NativeTokenVault,
}
}

26
node_modules/viem/zksync/actions/getGasPerPubdata.ts generated vendored Normal file
View File

@@ -0,0 +1,26 @@
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import { hexToBigInt } from '../../utils/encoding/fromHex.js'
import type { ChainEIP712 } from '../types/chain.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type GetGasPerPubdataReturnType = bigint
export async function getGasPerPubdata<
chain extends ChainEIP712 | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
): Promise<GetGasPerPubdataReturnType> {
const result = await client.request(
{
method: 'zks_gasPerPubdata',
},
{
dedupe: true,
},
)
return hexToBigInt(result)
}

43
node_modules/viem/zksync/actions/getL1Allowance.ts generated vendored Normal file
View File

@@ -0,0 +1,43 @@
import type { Address } from 'abitype'
import { parseAccount } from '../../accounts/utils/parseAccount.js'
import { readContract } from '../../actions/public/readContract.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { erc20Abi } from '../../constants/abis.js'
import type { AccountNotFoundError } from '../../errors/account.js'
import type { BaseError } from '../../errors/base.js'
import type { Account, GetAccountParameter } from '../../types/account.js'
import type { BlockTag } from '../../types/block.js'
import type { Chain } from '../../types/chain.js'
export type GetL1AllowanceParameters<
account extends Account | undefined = Account | undefined,
> = GetAccountParameter<account> & {
bridgeAddress: Address
blockTag?: BlockTag | undefined
token: Address
}
export type GetL1AllowanceReturnType = bigint
export type GetL1AllowanceErrorType = AccountNotFoundError | BaseError
export async function getL1Allowance<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: GetL1AllowanceParameters<account>,
): Promise<GetL1AllowanceReturnType> {
const { token, bridgeAddress, blockTag, account: account_ } = parameters
const account = account_ ? parseAccount(account_) : client.account
return await readContract(client, {
abi: erc20Abi,
address: token,
functionName: 'allowance',
args: [account!.address, bridgeAddress],
blockTag: blockTag,
})
}

68
node_modules/viem/zksync/actions/getL1Balance.ts generated vendored Normal file
View File

@@ -0,0 +1,68 @@
import type { Address } from 'abitype'
import { parseAccount } from '../../accounts/utils/parseAccount.js'
import {
type GetBalanceParameters,
getBalance,
} from '../../actions/public/getBalance.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { AccountNotFoundError } from '../../errors/account.js'
import type { BaseError } from '../../errors/base.js'
import type { Account, GetAccountParameter } from '../../types/account.js'
import type { BlockTag } from '../../types/block.js'
import type { Chain } from '../../types/chain.js'
import { legacyEthAddress } from '../constants/address.js'
import { isEth } from '../utils/isEth.js'
import {
type GetL1TokenBalanceParameters,
getL1TokenBalance,
} from './getL1TokenBalance.js'
export type GetL1BalanceParameters<
account extends Account | undefined = Account | undefined,
> = GetAccountParameter<account> & { token?: Address | undefined } & (
| {
/** The balance of the account at a block number. */
blockNumber?: bigint | undefined
blockTag?: undefined
}
| {
blockNumber?: undefined
/** The balance of the account at a block tag. */
blockTag?: BlockTag | undefined
}
)
export type GetL1BalanceReturnType = bigint
export type GetL1BalanceErrorType = AccountNotFoundError | BaseError
export async function getL1Balance<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
...[parameters = {}]: account extends undefined
? [GetL1BalanceParameters<account>]
: [GetL1BalanceParameters<account>] | []
): Promise<GetL1BalanceReturnType> {
const {
account: account_ = client.account,
blockNumber,
blockTag,
token = legacyEthAddress,
} = parameters
const account = account_ ? parseAccount(account_) : undefined
if (isEth(token))
return await getBalance(client, {
address: account!.address,
blockNumber,
blockTag,
} as GetBalanceParameters)
return await getL1TokenBalance(client, {
...(parameters as GetL1TokenBalanceParameters<account>),
})
}

View File

@@ -0,0 +1,26 @@
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import { hexToNumber } from '../../utils/encoding/fromHex.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type GetL1BatchBlockRangeParameters = {
l1BatchNumber: number
}
export type GetL1BatchBlockRangeReturnParameters = [number, number]
export async function getL1BatchBlockRange<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
parameters: GetL1BatchBlockRangeParameters,
): Promise<GetL1BatchBlockRangeReturnParameters> {
const [number_1, number_2] = await client.request({
method: 'zks_getL1BatchBlockRange',
params: [parameters.l1BatchNumber],
})
return [hexToNumber(number_1), hexToNumber(number_2)]
}

27
node_modules/viem/zksync/actions/getL1BatchDetails.ts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import type {
ZksyncBatchDetails,
ZksyncNumberParameter,
} from '../types/block.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type GetL1BatchDetailsParameters = ZksyncNumberParameter
export type GetL1BatchDetailsReturnType = ZksyncBatchDetails
export async function getL1BatchDetails<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
parameters: GetL1BatchDetailsParameters,
): Promise<GetL1BatchDetailsReturnType> {
const result = await client.request({
method: 'zks_getL1BatchDetails',
params: [parameters.number],
})
return result
}

18
node_modules/viem/zksync/actions/getL1BatchNumber.ts generated vendored Normal file
View File

@@ -0,0 +1,18 @@
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import type { Hex } from '../../types/misc.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type GetL1BatchNumberReturnType = Hex
export async function getL1BatchNumber<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
): Promise<GetL1BatchNumberReturnType> {
const result = await client.request({ method: 'zks_L1BatchNumber' })
return result
}

19
node_modules/viem/zksync/actions/getL1ChainId.ts generated vendored Normal file
View File

@@ -0,0 +1,19 @@
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import type { Hex } from '../../types/misc.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type GetL1ChainIdReturnType = Hex
/* @deprecated Use the `L1_CHAIN_ID()` method on the `L2AssetRouter` contract (deployed on `0x0000000000000000000000000000000000010003` address) */
export async function getL1ChainId<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
): Promise<GetL1ChainIdReturnType> {
const result = await client.request({ method: 'zks_L1ChainId' })
return result
}

59
node_modules/viem/zksync/actions/getL1TokenAddress.ts generated vendored Normal file
View File

@@ -0,0 +1,59 @@
import type { Address } from '../../accounts/index.js'
import { readContract } from '../../actions/public/readContract.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import { isAddressEqual } from '../../utils/index.js'
import { l2SharedBridgeAbi } from '../constants/abis.js'
import { legacyEthAddress } from '../constants/address.js'
import { getDefaultBridgeAddresses } from './getDefaultBridgeAddresses.js'
export type GetL1TokenAddressParameters = {
/** The address of the token on L2. */
token: Address
}
export type GetL1TokenAddressReturnType = Address
/**
* Returns the L1 token address equivalent for a L2 token address as they are not equal.
* ETH address is set to zero address.
*
* @remarks Only works for tokens bridged on default ZKsync Era bridges.
*
* @param client - Client to use
* @param parameters - {@link GetL1TokenAddressParameters}
* @returns The L1 token address equivalent for a L2 token address.
*
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksync } from 'viem/chains'
*
* const client = createPublicClient({
* chain: zksync,
* transport: http(),
* })
*
* const address = await getL1TokenAddress(client, {token: '0x...'});
*/
export async function getL1TokenAddress<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: GetL1TokenAddressParameters,
): Promise<Address> {
const { token } = parameters
if (isAddressEqual(token, legacyEthAddress)) return legacyEthAddress
const bridgeAddress = (await getDefaultBridgeAddresses(client)).sharedL2
return await readContract(client, {
address: bridgeAddress,
abi: l2SharedBridgeAbi,
functionName: 'l1TokenAddress',
args: [token],
})
}

66
node_modules/viem/zksync/actions/getL1TokenBalance.ts generated vendored Normal file
View File

@@ -0,0 +1,66 @@
import type { Address } from '../../accounts/index.js'
import { parseAccount } from '../../accounts/utils/parseAccount.js'
import { readContract } from '../../actions/index.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { erc20Abi } from '../../constants/abis.js'
import type { AccountNotFoundErrorType } from '../../errors/account.js'
import type { BaseErrorType } from '../../errors/base.js'
import type { Account, GetAccountParameter } from '../../types/account.js'
import type { BlockTag } from '../../types/block.js'
import type { Chain } from '../../types/chain.js'
import {
TokenIsEthError,
type TokenIsEthErrorType,
} from '../errors/token-is-eth.js'
import { isEth } from '../utils/isEth.js'
export type GetL1TokenBalanceParameters<
account extends Account | undefined = Account | undefined,
> = GetAccountParameter<account> & { token: Address } & (
| {
/** The balance of the account at a block number. */
blockNumber?: bigint | undefined
blockTag?: undefined
}
| {
blockNumber?: undefined
/** The balance of the account at a block tag. */
blockTag?: BlockTag | undefined
}
)
export type GetL1TokenBalanceReturnType = bigint
export type GetL1TokenBalanceErrorType =
| AccountNotFoundErrorType
| TokenIsEthErrorType
| BaseErrorType
export async function getL1TokenBalance<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: GetL1TokenBalanceParameters<account>,
): Promise<GetL1TokenBalanceReturnType> {
const {
account: account_ = client.account,
blockTag,
blockNumber,
token,
} = parameters
if (isEth(token!)) throw new TokenIsEthError()
const account = account_ ? parseAccount(account_) : client.account
return await readContract(client, {
abi: erc20Abi,
address: token!,
functionName: 'balanceOf',
args: [account!.address],
blockNumber: blockNumber,
blockTag: blockTag,
})
}

70
node_modules/viem/zksync/actions/getL2TokenAddress.ts generated vendored Normal file
View File

@@ -0,0 +1,70 @@
import type { Address } from '../../accounts/index.js'
import { readContract } from '../../actions/public/readContract.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import { isAddressEqual } from '../../utils/index.js'
import { l2SharedBridgeAbi } from '../constants/abis.js'
import {
ethAddressInContracts,
l2BaseTokenAddress,
legacyEthAddress,
} from '../constants/address.js'
import { getBaseTokenL1Address } from './getBaseTokenL1Address.js'
import { getDefaultBridgeAddresses } from './getDefaultBridgeAddresses.js'
export type GetL2TokenAddressParameters = {
/** The address of the token on L1. */
token: Address
/** The address of custom bridge, which will be used to get l2 token address. */
bridgeAddress?: Address | undefined
}
export type GetL2TokenAddressReturnType = Address
/**
* Returns the L2 token address equivalent for a L1 token address as they are not equal.
* ETH address is set to zero address.
*
* @remarks Only works for tokens bridged on default ZKsync Era bridges.
*
* @param client - Client to use
* @param parameters - {@link GetL2TokenAddressParameters}
* @returns The L2 token address equivalent for a L1 token address.
*
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksync } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const address = await getL2TokenAddress(client, {token: '0x...'});
*/
export async function getL2TokenAddress<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: GetL2TokenAddressParameters,
): Promise<Address> {
let { token, bridgeAddress } = parameters
if (isAddressEqual(token, legacyEthAddress)) token = ethAddressInContracts
const baseToken = await getBaseTokenL1Address(client)
if (isAddressEqual(token, baseToken)) return l2BaseTokenAddress
bridgeAddress ??= (await getDefaultBridgeAddresses(client)).sharedL2
return await readContract(client, {
address: bridgeAddress,
abi: l2SharedBridgeAbi,
functionName: 'l2TokenAddress',
args: [token],
})
}

28
node_modules/viem/zksync/actions/getLogProof.ts generated vendored Normal file
View File

@@ -0,0 +1,28 @@
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import type { Hash } from '../../types/misc.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
import type { MessageProof } from '../types/proof.js'
export type GetLogProofParameters = {
txHash: Hash
index?: number | undefined
}
export type GetLogProofReturnType = MessageProof | null
export async function getLogProof<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
parameters: GetLogProofParameters,
): Promise<MessageProof | null> {
const result = await client.request({
method: 'zks_getL2ToL1LogProof',
params: [parameters.txHash, parameters.index],
})
return result
}

View File

@@ -0,0 +1,19 @@
import type { Address } from 'abitype'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type GetMainContractAddressReturnType = Address
/* @deprecated Use `getBridgeHubContractAddress` and call `getZKChain(chainId)` instead. */
export async function getMainContractAddress<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
): Promise<GetMainContractAddressReturnType> {
const address = await client.request({ method: 'zks_getMainContract' })
return address
}

View File

@@ -0,0 +1,27 @@
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import type { ZksyncNumberParameter } from '../types/block.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
import type { ZksyncRawBlockTransactions } from '../types/transaction.js'
import { camelCaseKeys } from '../utils/camelCaseKeys.js'
export type GetRawBlockTransactionsParameters = ZksyncNumberParameter
export type GetRawBlockTransactionsReturnType = ZksyncRawBlockTransactions
/* @deprecated Use `debug_getRawTransaction` and `debug_getRawTransactions` instead. */
export async function getRawBlockTransactions<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
parameters: GetRawBlockTransactionsParameters,
): Promise<GetRawBlockTransactionsReturnType> {
const result = await client.request({
method: 'zks_getRawBlockTransactions',
params: [parameters.number],
})
return camelCaseKeys(result) as GetRawBlockTransactionsReturnType
}

View File

@@ -0,0 +1,19 @@
import type { Address } from 'abitype'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
export type GetTestnetPaymasterAddressReturnType = Address | null
/* @deprecated Check the corresponding ZKsync chain technical documentation to find the testnet paymaster address */
export async function getTestnetPaymasterAddress<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
): Promise<GetTestnetPaymasterAddressReturnType> {
const result = await client.request({ method: 'zks_getTestnetPaymaster' })
return result
}

View File

@@ -0,0 +1,27 @@
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import type { Hash } from '../../types/misc.js'
import type { PublicZksyncRpcSchema } from '../types/eip1193.js'
import type { ZksyncTransactionDetails } from '../types/transaction.js'
export type GetTransactionDetailsParameters = {
txHash: Hash
}
export type GetTransactionDetailsReturnType = ZksyncTransactionDetails
export async function getTransactionDetails<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account, PublicZksyncRpcSchema>,
parameters: GetTransactionDetailsParameters,
): Promise<GetTransactionDetailsReturnType> {
const result = await client.request({
method: 'zks_getTransactionDetails',
params: [parameters.txHash],
})
return result
}

View File

@@ -0,0 +1,104 @@
import type { Account } from '../../accounts/types.js'
import { readContract } from '../../actions/public/readContract.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import {
ChainNotFoundError,
type ChainNotFoundErrorType,
} from '../../errors/chain.js'
import type { Chain } from '../../types/chain.js'
import type { Hash } from '../../types/misc.js'
import { l1SharedBridgeAbi } from '../constants/abis.js'
import {
WithdrawalLogNotFoundError,
type WithdrawalLogNotFoundErrorType,
} from '../errors/bridge.js'
import type { ChainEIP712 } from '../types/chain.js'
import { getWithdrawalL2ToL1Log } from '../utils/bridge/getWithdrawalL2ToL1Log.js'
import { getWithdrawalLog } from '../utils/bridge/getWithdrawalLog.js'
import { getDefaultBridgeAddresses } from './getDefaultBridgeAddresses.js'
import { getLogProof } from './getLogProof.js'
export type IsWithdrawalFinalizedParameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = {
/** L2 client */
client: Client<Transport, chain, account>
/** Hash of the L2 transaction where the withdrawal was initiated. */
hash: Hash
/** In case there were multiple withdrawals in one transaction, you may pass an index of the
withdrawal you want to finalize. */
index?: number | undefined
}
export type IsWithdrawalFinalizedReturnType = boolean
export type IsWithdrawalFinalizedErrorType =
| WithdrawalLogNotFoundErrorType
| ChainNotFoundErrorType
/**
* Returns whether the withdrawal transaction is finalized on the L1 network.
*
* @param client - Client to use
* @param parameters - {@link IsWithdrawalFinalizedParameters}
* @returns bool - Whether the withdrawal transaction is finalized on the L1 network. {@link IsWithdrawalFinalizedReturnType}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { mainnet, zksync } from 'viem/chains'
* import { isWithdrawalFinalized } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* })
*
* const hash = await isWithdrawalFinalized(client, {
* client: clientL2,
* hash: '0x...',
* })
*/
export async function isWithdrawalFinalized<
chain extends Chain | undefined,
account extends Account | undefined,
chainL2 extends ChainEIP712 | undefined,
accountL2 extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: IsWithdrawalFinalizedParameters<chainL2, accountL2>,
): Promise<IsWithdrawalFinalizedReturnType> {
const { client: l2Client, hash, index = 0 } = parameters
if (!l2Client.chain) throw new ChainNotFoundError()
const { log } = await getWithdrawalLog(l2Client, { hash, index })
const { l2ToL1LogIndex } = await getWithdrawalL2ToL1Log(l2Client, {
hash,
index,
})
// `getLogProof` is called not to get proof but
// to get the index of the corresponding L2->L1 log,
// which is returned as `proof.id`.
const proof = await getLogProof(l2Client, {
txHash: hash,
index: l2ToL1LogIndex!,
})
if (!proof) throw new WithdrawalLogNotFoundError({ hash })
const l1Bridge = (await getDefaultBridgeAddresses(l2Client)).sharedL1
return await readContract(client, {
address: l1Bridge,
abi: l1SharedBridgeAbi,
functionName: 'isWithdrawalFinalized',
args: [BigInt(l2Client.chain.id), log.l1BatchNumber!, BigInt(proof.id)],
})
}

282
node_modules/viem/zksync/actions/requestExecute.ts generated vendored Normal file
View File

@@ -0,0 +1,282 @@
import type { Address } from 'abitype'
import { generatePrivateKey } from '../../accounts/generatePrivateKey.js'
import type { Account } from '../../accounts/types.js'
import { privateKeyToAddress } from '../../accounts/utils/privateKeyToAddress.js'
import { readContract } from '../../actions/public/readContract.js'
import {
type SendTransactionErrorType,
type SendTransactionParameters,
type SendTransactionReturnType,
sendTransaction,
} from '../../actions/wallet/sendTransaction.js'
import type { Client } from '../../clients/createClient.js'
import { publicActions } from '../../clients/decorators/public.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { AccountNotFoundError } from '../../errors/account.js'
import { ClientChainNotConfiguredError } from '../../errors/chain.js'
import type { GetAccountParameter } from '../../types/account.js'
import type {
Chain,
DeriveChain,
GetChainParameter,
} from '../../types/chain.js'
import type { Hex } from '../../types/misc.js'
import type { UnionEvaluate, UnionOmit } from '../../types/utils.js'
import {
encodeFunctionData,
type FormattedTransactionRequest,
isAddressEqual,
parseAccount,
} from '../../utils/index.js'
import { bridgehubAbi } from '../constants/abis.js'
import { ethAddressInContracts } from '../constants/address.js'
import { requiredL1ToL2GasPerPubdataLimit } from '../constants/number.js'
import {
BaseFeeHigherThanValueError,
type BaseFeeHigherThanValueErrorType,
} from '../errors/bridge.js'
import type { ChainEIP712 } from '../types/chain.js'
import { estimateGasL1ToL2 } from './estimateGasL1ToL2.js'
import { getBridgehubContractAddress } from './getBridgehubContractAddress.js'
export type RequestExecuteParameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
chainL2 extends ChainEIP712 | undefined = ChainEIP712 | undefined,
accountL2 extends Account | undefined = Account | undefined,
_derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,
> = UnionEvaluate<
UnionOmit<FormattedTransactionRequest<_derivedChain>, 'data' | 'to' | 'from'>
> &
Partial<GetChainParameter<chain, chainOverride>> &
Partial<GetAccountParameter<account>> & {
/** L2 client. */
client: Client<Transport, chainL2, accountL2>
/** The L2 contract to be called. */
contractAddress: Address
/** The input of the L2 transaction. */
calldata: Hex
/** Maximum amount of L2 gas that transaction can consume during execution on L2. */
l2GasLimit?: bigint | undefined
/** The amount of base token that needs to be minted on non-ETH-based L2. */
mintValue?: bigint | undefined
/** The `msg.value` of L2 transaction. */
l2Value?: bigint | undefined
/** An array of L2 bytecodes that will be marked as known on L2. */
factoryDeps?: Hex[] | undefined
/** (currently not used) The tip the operator will receive on top of
the base cost of the transaction. */
operatorTip?: bigint | undefined
/** The L2 gas price for each published L1 calldata byte. */
gasPerPubdataByte?: bigint | undefined
/** The address on L2 that will receive the refund for the transaction.
If the transaction fails, it will also be the address to receive `l2Value`. */
refundRecipient?: Address | undefined
}
export type RequestExecuteReturnType = SendTransactionReturnType
export type RequestExecuteErrorType =
| SendTransactionErrorType
| BaseFeeHigherThanValueErrorType
/**
* Requests execution of a L2 transaction from L1.
*
* @param client - Client to use
* @param parameters - {@link RequestExecuteParameters}
* @returns hash - The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link RequestExecuteReturnType}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync, mainnet } from 'viem/chains'
* import { requestExecute, publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await requestExecute(client, {
* client: clientL2,
* account: privateKeyToAccount('0x…'),
* contractAddress: '0x43020e6e11cef7dce8e37baa09d9a996ac722057'
* calldata: '0x',
* l2Value: 1_000_000_000_000_000_000n,
* })
*
* @example Account Hoisting
* import { createPublicClient, createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync, mainnet } from 'viem/chains'
* import { requestExecute, publicActionsL2 } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: mainnet,
* transport: http(),
* })
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await requestExecute(client, {
* client: clientL2,
* contractAddress: '0x43020e6e11cef7dce8e37baa09d9a996ac722057'
* calldata: '0x',
* l2Value: 1_000_000_000_000_000_000n,
* })
*/
export async function requestExecute<
chain extends Chain | undefined,
account extends Account | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
chainL2 extends ChainEIP712 | undefined = ChainEIP712 | undefined,
accountL2 extends Account | undefined = Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: RequestExecuteParameters<
chain,
account,
chainOverride,
chainL2,
accountL2
>,
): Promise<RequestExecuteReturnType> {
let {
account: account_ = client.account,
chain: chain_ = client.chain,
client: l2Client,
contractAddress,
calldata,
l2Value = 0n,
mintValue = 0n,
operatorTip = 0n,
factoryDeps = [],
gasPerPubdataByte = requiredL1ToL2GasPerPubdataLimit,
refundRecipient,
l2GasLimit,
value,
gasPrice,
maxFeePerGas,
maxPriorityFeePerGas,
...rest
} = parameters
const account = account_ ? parseAccount(account_) : client.account
if (!account)
throw new AccountNotFoundError({
docsPath: '/docs/actions/wallet/sendTransaction',
})
if (!l2Client.chain) throw new ClientChainNotConfiguredError()
const bridgehub = await getBridgehubContractAddress(l2Client)
const baseToken = await readContract(client, {
address: bridgehub,
abi: bridgehubAbi,
functionName: 'baseToken',
args: [BigInt(l2Client.chain.id)],
})
const isETHBasedChain = isAddressEqual(baseToken, ethAddressInContracts)
refundRecipient ??= account.address
l2GasLimit ??= await estimateGasL1ToL2(l2Client, {
chain: l2Client.chain,
// If the `from` address is not provided, we use a random address, because
// due to storage slot aggregation, the gas estimation will depend on the address
// and so estimation for the zero address may be smaller than for the sender.
account:
l2Client.account ??
parseAccount(privateKeyToAddress(generatePrivateKey())),
data: calldata,
to: contractAddress,
value: l2Value,
gasPerPubdata: gasPerPubdataByte,
factoryDeps,
})
let gasPriceForEstimation = maxFeePerGas || gasPrice
if (!gasPriceForEstimation) {
const estimatedFee = await getFeePrice(client)
gasPriceForEstimation = estimatedFee.maxFeePerGas
maxFeePerGas = estimatedFee.maxFeePerGas
maxPriorityFeePerGas ??= estimatedFee.maxPriorityFeePerGas
}
const baseCost = await readContract(client, {
address: bridgehub,
abi: bridgehubAbi,
functionName: 'l2TransactionBaseCost',
args: [
BigInt(l2Client.chain.id),
gasPriceForEstimation,
l2GasLimit,
gasPerPubdataByte,
],
})
const l2Costs = baseCost + operatorTip + l2Value
let providedValue = isETHBasedChain ? value : mintValue
if (!providedValue || providedValue === 0n) {
providedValue = l2Costs
}
if (baseCost > providedValue)
throw new BaseFeeHigherThanValueError(baseCost, providedValue)
const data = encodeFunctionData({
abi: bridgehubAbi,
functionName: 'requestL2TransactionDirect',
args: [
{
chainId: BigInt(l2Client.chain.id),
mintValue: providedValue,
l2Contract: contractAddress,
l2Value: l2Value,
l2Calldata: calldata,
l2GasLimit: l2GasLimit,
l2GasPerPubdataByteLimit: gasPerPubdataByte,
factoryDeps: factoryDeps,
refundRecipient: refundRecipient,
},
],
})
return await sendTransaction(client, {
chain: chain_,
account: account,
to: bridgehub,
value: isETHBasedChain ? providedValue : value,
data,
gasPrice,
maxFeePerGas,
maxPriorityFeePerGas,
...rest,
} as SendTransactionParameters)
}
async function getFeePrice<chain extends Chain | undefined>(
client: Client<Transport, chain>,
) {
const client_ = client.extend(publicActions)
const block = await client_.getBlock()
const baseFee =
typeof block.baseFeePerGas !== 'bigint'
? await client_.getGasPrice()
: block.baseFeePerGas
const maxPriorityFeePerGas = await client_.estimateMaxPriorityFeePerGas()
return {
maxFeePerGas: (baseFee * 3n) / 2n + maxPriorityFeePerGas,
maxPriorityFeePerGas: maxPriorityFeePerGas,
}
}

View File

@@ -0,0 +1,143 @@
import type { Account } from '../../accounts/types.js'
import { parseAccount } from '../../accounts/utils/parseAccount.js'
import { getChainId } from '../../actions/public/getChainId.js'
import { prepareTransactionRequest } from '../../actions/wallet/prepareTransactionRequest.js'
import { sendRawTransaction } from '../../actions/wallet/sendRawTransaction.js'
import type {
SendTransactionErrorType,
SendTransactionParameters,
SendTransactionRequest,
SendTransactionReturnType,
} from '../../actions/wallet/sendTransaction.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { AccountNotFoundError } from '../../errors/account.js'
import type { BaseError } from '../../errors/base.js'
import type { Chain } from '../../types/chain.js'
import { assertCurrentChain } from '../../utils/chain/assertCurrentChain.js'
import {
type GetTransactionErrorParameters,
getTransactionError,
} from '../../utils/errors/getTransactionError.js'
import { getAction } from '../../utils/getAction.js'
import type { ChainEIP712 } from '../types/chain.js'
import { assertEip712Request } from '../utils/assertEip712Request.js'
import { signTransaction } from './signTransaction.js'
export type SendEip712TransactionParameters<
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends ChainEIP712 | undefined = ChainEIP712 | undefined,
request extends SendTransactionRequest<
chain,
chainOverride
> = SendTransactionRequest<chain, chainOverride>,
> = SendTransactionParameters<chain, account, chainOverride, request>
export type SendEip712TransactionReturnType = SendTransactionReturnType
export type SendEip712TransactionErrorType = SendTransactionErrorType
/**
* Creates, signs, and sends a new EIP712 transaction to the network.
*
* @param client - Client to use
* @param parameters - {@link SendEip712TransactionParameters}
* @returns The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link SendTransactionReturnType}
*
* @example
* import { createWalletClient, custom } from 'viem'
* import { zksync } from 'viem/chains'
* import { sendEip712Transaction } from 'viem/zksync'
*
* const client = createWalletClient({
* chain: zksync,
* transport: custom(window.ethereum),
* })
* const hash = await sendEip712Transaction(client, {
* account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
* to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
* value: 1000000000000000000n,
* })
*
* @example
* // Account Hoisting
* import { createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { sendEip712Transaction } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: zksync,
* transport: http(),
* })
*
* const hash = await sendEip712Transaction(client, {
* to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
* value: 1000000000000000000n,
* })
*/
export async function sendEip712Transaction<
chain extends ChainEIP712 | undefined,
account extends Account | undefined,
const request extends SendTransactionRequest<chain, chainOverride>,
chainOverride extends ChainEIP712 | undefined = undefined,
>(
client: Client<Transport, chain, account>,
parameters: SendEip712TransactionParameters<
chain,
account,
chainOverride,
request
>,
): Promise<SendEip712TransactionReturnType> {
const { account: account_ = client.account, chain = client.chain } =
parameters
const account = account_ ? parseAccount(account_) : client.account
if (!account)
throw new AccountNotFoundError({
docsPath: '/docs/actions/wallet/sendTransaction',
})
try {
assertEip712Request(parameters)
// Prepare the request for signing (assign appropriate fees, etc.)
const request = await prepareTransactionRequest(client, {
...parameters,
nonceManager: account.nonceManager,
parameters: ['gas', 'nonce', 'fees'],
} as any)
let chainId: number | undefined
if (chain !== null) {
chainId = await getAction(client, getChainId, 'getChainId')({})
assertCurrentChain({
currentChainId: chainId,
chain,
})
}
const serializedTransaction = await signTransaction(client, {
...request,
chainId,
} as any)
return await getAction(
client,
sendRawTransaction,
'sendRawTransaction',
)({
serializedTransaction,
})
} catch (err) {
throw getTransactionError(err as BaseError, {
...(parameters as GetTransactionErrorParameters),
account,
chain: chain as Chain,
})
}
}

94
node_modules/viem/zksync/actions/sendTransaction.ts generated vendored Normal file
View File

@@ -0,0 +1,94 @@
import type { Account } from '../../accounts/types.js'
import type {
SendTransactionErrorType as core_SendTransactionErrorType,
SendTransactionParameters as core_SendTransactionParameters,
SendTransactionReturnType as core_SendTransactionReturnType,
SendTransactionRequest,
} from '../../actions/wallet/sendTransaction.js'
import { sendTransaction as core_sendTransaction } from '../../actions/wallet/sendTransaction.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { ChainEIP712 } from '../types/chain.js'
import { isEIP712Transaction } from '../utils/isEip712Transaction.js'
import {
type SendEip712TransactionParameters,
sendEip712Transaction,
} from './sendEip712Transaction.js'
export type SendTransactionParameters<
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends ChainEIP712 | undefined = ChainEIP712 | undefined,
request extends SendTransactionRequest<
chain,
chainOverride
> = SendTransactionRequest<chain, chainOverride>,
> = core_SendTransactionParameters<chain, account, chainOverride, request>
export type SendTransactionReturnType = core_SendTransactionReturnType
export type SendTransactionErrorType = core_SendTransactionErrorType
/**
* Creates, signs, and sends a new transaction to the network.
*
* - Docs: https://viem.sh/docs/zksync/actions/sendTransaction
* - JSON-RPC Methods:
* - JSON-RPC Accounts: [`eth_sendTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction)
* - Local Accounts: [`eth_sendRawTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendrawtransaction)
*
* @param client - Client to use
* @param parameters - {@link SendTransactionParameters}
* @returns The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link SendTransactionReturnType}
*
* @example
* import { createWalletClient, custom } from 'viem'
* import { zksync } from 'viem/chains'
* import { sendTransaction } from 'viem/zksync'
*
* const client = createWalletClient({
* chain: zksync,
* transport: custom(window.ethereum),
* })
* const hash = await sendTransaction(client, {
* account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
* to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
* value: 1000000000000000000n,
* })
*
* @example
* // Account Hoisting
* import { createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { sendTransaction } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: zksync,
* transport: http(),
* })
* const hash = await sendTransaction(client, {
* to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
* value: 1000000000000000000n,
* })
*/
export async function sendTransaction<
chain extends ChainEIP712 | undefined,
account extends Account | undefined,
const request extends SendTransactionRequest<chain, chainOverride>,
chainOverride extends ChainEIP712 | undefined = undefined,
>(
client: Client<Transport, chain, account>,
parameters: SendTransactionParameters<chain, account, chainOverride, request>,
): Promise<SendTransactionReturnType> {
if (isEIP712Transaction(parameters))
return sendEip712Transaction(
client,
parameters as SendEip712TransactionParameters,
)
return core_sendTransaction(
client,
parameters as core_SendTransactionParameters,
)
}

View File

@@ -0,0 +1,153 @@
import type { Account } from '../../accounts/types.js'
import { parseAccount } from '../../accounts/utils/parseAccount.js'
import { getChainId } from '../../actions/public/getChainId.js'
import type {
SignTransactionErrorType,
SignTransactionReturnType,
} from '../../actions/wallet/signTransaction.js'
import { signTypedData } from '../../actions/wallet/signTypedData.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { AccountNotFoundError } from '../../errors/account.js'
import { BaseError } from '../../errors/base.js'
import type { GetAccountParameter } from '../../types/account.js'
import type {
ExtractChainFormatterParameters,
GetChainParameter,
} from '../../types/chain.js'
import type { UnionOmit } from '../../types/utils.js'
import { assertCurrentChain } from '../../utils/chain/assertCurrentChain.js'
import { getAction } from '../../utils/getAction.js'
import type { ChainEIP712 } from '../types/chain.js'
import type { TransactionRequestEIP712 } from '../types/transaction.js'
import {
type AssertEip712RequestParameters,
assertEip712Request,
} from '../utils/assertEip712Request.js'
type FormattedTransactionRequest<
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
> = ExtractChainFormatterParameters<
chain,
'transactionRequest',
TransactionRequestEIP712
>
export type SignEip712TransactionParameters<
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends ChainEIP712 | undefined = ChainEIP712 | undefined,
> = UnionOmit<
FormattedTransactionRequest<
chainOverride extends ChainEIP712 ? chainOverride : chain
>,
'from'
> &
GetAccountParameter<account> &
GetChainParameter<chain, chainOverride>
export type SignEip712TransactionReturnType = SignTransactionReturnType
export type SignEip712TransactionErrorType = SignTransactionErrorType
/**
* Signs an EIP712 transaction.
*
*
* @param client - Client to use
* @param args - {@link SignTransactionParameters}
* @returns The signed serialized transaction. {@link SignTransactionReturnType}
*
* @example
* import { createWalletClient, custom } from 'viem'
* import { zksync } from 'viem/chains'
* import { signEip712Transaction } from 'viem/zksync'
*
* const client = createWalletClient({
* chain: zksync,
* transport: custom(window.ethereum),
* })
* const signature = await signEip712Transaction(client, {
* account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
* to: '0x0000000000000000000000000000000000000000',
* value: 1n,
* })
*
* @example
* // Account Hoisting
* import { createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { signEip712Transaction } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: zksync,
* transport: custom(window.ethereum),
* })
* const signature = await signEip712Transaction(client, {
* to: '0x0000000000000000000000000000000000000000',
* value: 1n,
* })
*/
export async function signEip712Transaction<
chain extends ChainEIP712 | undefined,
account extends Account | undefined,
chainOverride extends ChainEIP712 | undefined,
>(
client: Client<Transport, chain, account>,
args: SignEip712TransactionParameters<chain, account, chainOverride>,
): Promise<SignEip712TransactionReturnType> {
const {
account: account_ = client.account,
chain = client.chain,
...transaction
} = args
const account = account_ ? parseAccount(account_) : client.account
if (!account)
throw new AccountNotFoundError({
docsPath: '/docs/actions/wallet/signTransaction',
})
assertEip712Request({
account,
chain,
...(args as AssertEip712RequestParameters),
})
if (!chain?.custom?.getEip712Domain)
throw new BaseError('`getEip712Domain` not found on chain.')
if (!chain?.serializers?.transaction)
throw new BaseError('transaction serializer not found on chain.')
const chainId = await getAction(client, getChainId, 'getChainId')({})
if (chain !== null)
assertCurrentChain({
currentChainId: chainId,
chain: chain,
})
const eip712Domain = chain?.custom.getEip712Domain({
...transaction,
chainId,
from: account.address,
type: 'eip712',
})
const customSignature = await signTypedData(client, {
...eip712Domain,
account,
})
return chain?.serializers?.transaction(
{
chainId,
...transaction,
customSignature,
type: 'eip712' as any,
},
{ r: '0x0', s: '0x0', v: 0n },
) as SignEip712TransactionReturnType
}

95
node_modules/viem/zksync/actions/signTransaction.ts generated vendored Normal file
View File

@@ -0,0 +1,95 @@
import type { Account } from '../../accounts/types.js'
import type {
SignTransactionErrorType as SignTransactionErrorType_,
SignTransactionReturnType as SignTransactionReturnType_,
} from '../../actions/wallet/signTransaction.js'
import { signTransaction as signTransaction_ } from '../../actions/wallet/signTransaction.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { GetAccountParameter } from '../../types/account.js'
import type {
ExtractChainFormatterParameters,
GetChainParameter,
} from '../../types/chain.js'
import type { UnionOmit } from '../../types/utils.js'
import type { ChainEIP712 } from '../types/chain.js'
import type { TransactionRequestEIP712 } from '../types/transaction.js'
import { isEIP712Transaction } from '../utils/isEip712Transaction.js'
import { signEip712Transaction } from './signEip712Transaction.js'
type FormattedTransactionRequest<
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
> = ExtractChainFormatterParameters<
chain,
'transactionRequest',
TransactionRequestEIP712
>
export type SignTransactionParameters<
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends ChainEIP712 | undefined = ChainEIP712 | undefined,
> = UnionOmit<
FormattedTransactionRequest<
chainOverride extends ChainEIP712 ? chainOverride : chain
>,
'from'
> &
GetAccountParameter<account> &
GetChainParameter<chain, chainOverride>
export type SignTransactionReturnType = SignTransactionReturnType_
export type SignTransactionErrorType = SignTransactionErrorType_
/**
* Signs a transaction.
*
* - Docs: https://viem.sh/docs/zksync/actions/signTransaction
*
* @param args - {@link SignTransactionParameters}
* @returns The signed serialized transaction. {@link SignTransactionReturnType}
*
* @example
* import { createWalletClient, custom } from 'viem'
* import { zksync } from 'viem/chains'
* import { signTransaction } from 'viem/zksync'
*
* const client = createWalletClient({
* chain: zksync,
* transport: custom(window.ethereum),
* })
* const signature = await signTransaction(client, {
* account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
* to: '0x0000000000000000000000000000000000000000',
* value: 1n,
* })
*
* @example
* // Account Hoisting
* import { createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { signTransaction } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: zksync,
* transport: custom(window.ethereum),
* })
* const signature = await signTransaction(client, {
* to: '0x0000000000000000000000000000000000000000',
* value: 1n,
* })
*/
export async function signTransaction<
chain extends ChainEIP712 | undefined,
account extends Account | undefined,
chainOverride extends ChainEIP712 | undefined,
>(
client: Client<Transport, chain, account>,
args: SignTransactionParameters<chain, account, chainOverride>,
): Promise<SignTransactionReturnType> {
if (isEIP712Transaction(args)) return signEip712Transaction(client, args)
return await signTransaction_(client, args as any)
}

241
node_modules/viem/zksync/actions/withdraw.ts generated vendored Normal file
View File

@@ -0,0 +1,241 @@
import { type Address, parseAbi } from 'abitype'
import type { Account } from '../../accounts/types.js'
import { readContract } from '../../actions/public/readContract.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { AccountNotFoundError } from '../../errors/account.js'
import { ClientChainNotConfiguredError } from '../../errors/chain.js'
import type { GetAccountParameter } from '../../types/account.js'
import type { GetChainParameter } from '../../types/chain.js'
import type { UnionOmit } from '../../types/utils.js'
import type { EncodeFunctionDataReturnType } from '../../utils/abi/encodeFunctionData.js'
import {
encodeAbiParameters,
encodeFunctionData,
isAddressEqual,
keccak256,
parseAccount,
} from '../../utils/index.js'
import { ethTokenAbi, l2SharedBridgeAbi } from '../constants/abis.js'
import {
ethAddressInContracts,
l2AssetRouterAddress,
l2BaseTokenAddress,
l2NativeTokenVaultAddress,
legacyEthAddress,
} from '../constants/address.js'
import type { ChainEIP712 } from '../types/chain.js'
import type { ZksyncTransactionRequest } from '../types/transaction.js'
import { getDefaultBridgeAddresses } from './getDefaultBridgeAddresses.js'
import { getL1ChainId } from './getL1ChainId.js'
import { getL2TokenAddress } from './getL2TokenAddress.js'
import {
type SendTransactionErrorType,
type SendTransactionParameters,
type SendTransactionReturnType,
sendTransaction,
} from './sendTransaction.js'
export type WithdrawParameters<
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends ChainEIP712 | undefined = ChainEIP712 | undefined,
> = UnionOmit<
ZksyncTransactionRequest,
'from' | 'type' | 'value' | 'data' | 'to' | 'factoryDeps' | 'maxFeePerBlobGas'
> &
Partial<GetAccountParameter<account>> &
Partial<GetChainParameter<chain, chainOverride>> & {
/** The address of the recipient on L1. Defaults to the sender address. */
to?: Address | undefined
/** The address of the token. */
token: Address
/** The amount of the token to withdraw. */
amount: bigint
/** The address of the bridge contract to be used. */
bridgeAddress?: Address | undefined
}
export type WithdrawReturnType = SendTransactionReturnType
export type WithdrawErrorType = SendTransactionErrorType
/**
* Initiates the withdrawal process which withdraws ETH or any ERC20 token
* from the associated account on L2 network to the target account on L1 network.
*
* @param client - Client to use
* @param parameters - {@link WithdrawParameters}
* @returns hash - The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link WithdrawReturnType}
*
*
* @example
* import { createPublicClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { withdraw, legacyEthAddress } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksync,
* transport: http(),
* })
*
* const hash = await withdraw(client, {
* account: privateKeyToAccount('0x…'),
* amount: 1_000_000_000_000_000_000n,
* token: legacyEthAddress,
* })
*
* @example Account Hoisting
* import { createPublicClient, createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { withdraw, legacyEthAddress } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: zksync,
* transport: http(),
* })
*
* const hash = await withdraw(client, {
* amount: 1_000_000_000_000_000_000n,
* token: legacyEthAddress,
* })
*
* @example Paymaster
* import { createPublicClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import {
* withdraw,
* legacyEthAddress,
* getApprovalBasedPaymasterInput
* } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksync,
* transport: http(),
* })
*
* const hash = await withdraw(client, {
* account: privateKeyToAccount('0x…'),
* amount: 1_000_000_000_000_000_000n,
* token: legacyEthAddress,
* paymaster: '0x0EEc6f45108B4b806e27B81d9002e162BD910670',
* paymasterInput: getApprovalBasedPaymasterInput({
* minAllowance: 1n,
* token: '0x2dc3685cA34163952CF4A5395b0039c00DFa851D',
* innerInput: new Uint8Array(),
* }),
* })
*/
export async function withdraw<
chain extends ChainEIP712 | undefined,
account extends Account | undefined,
chainOverride extends ChainEIP712 | undefined = undefined,
>(
client: Client<Transport, chain, account>,
parameters: WithdrawParameters<chain, account, chainOverride>,
): Promise<WithdrawReturnType> {
let {
account: account_ = client.account,
chain: chain_ = client.chain,
token = l2BaseTokenAddress,
to,
amount,
bridgeAddress,
...rest
} = parameters
const account = account_ ? parseAccount(account_) : client.account
if (!account)
throw new AccountNotFoundError({
docsPath: '/docs/actions/wallet/sendTransaction',
})
if (!to) to = account.address
let data: EncodeFunctionDataReturnType
let contract: Address
let value = 0n
if (
isAddressEqual(token, legacyEthAddress) ||
isAddressEqual(token, ethAddressInContracts)
)
token = await getL2TokenAddress(client, { token: ethAddressInContracts })
if (isAddressEqual(token, l2BaseTokenAddress)) {
data = encodeFunctionData({
abi: ethTokenAbi,
functionName: 'withdraw',
args: [to],
})
value = amount
contract = l2BaseTokenAddress
} else {
const assetId = await readContract(client, {
address: l2NativeTokenVaultAddress,
abi: parseAbi(['function assetId(address token) view returns (bytes32)']),
functionName: 'assetId',
args: [token],
})
const originChainId = await readContract(client, {
address: l2NativeTokenVaultAddress,
abi: parseAbi([
'function originChainId(bytes32 assetId) view returns (uint256)',
]),
functionName: 'originChainId',
args: [assetId],
})
const l1ChainId = await getL1ChainId(client)
const isTokenL1Native =
originChainId === BigInt(l1ChainId) || token === ethAddressInContracts
if (!bridgeAddress) {
// If the legacy L2SharedBridge is deployed we use it for l1 native tokens.
bridgeAddress = isTokenL1Native
? (await getDefaultBridgeAddresses(client)).sharedL2
: l2AssetRouterAddress
}
// For non L1 native tokens we need to use the AssetRouter.
// For L1 native tokens we can use the legacy withdraw method.
if (!isTokenL1Native) {
contract = l2AssetRouterAddress
if (!chain_) throw new ClientChainNotConfiguredError()
const chainId = chain_.id
const assetId = keccak256(
encodeAbiParameters(
[{ type: 'uint256' }, { type: 'address' }, { type: 'address' }],
[BigInt(chainId), l2NativeTokenVaultAddress, token],
),
)
const assetData = encodeAbiParameters(
[{ type: 'uint256' }, { type: 'address' }, { type: 'address' }],
[BigInt(amount), to, token],
)
data = encodeFunctionData({
abi: parseAbi([
'function withdraw(bytes32 _assetId, bytes _transferData)',
]),
functionName: 'withdraw',
args: [assetId, assetData],
})
} else {
contract = bridgeAddress
data = encodeFunctionData({
abi: l2SharedBridgeAbi,
functionName: 'withdraw',
args: [to, token, amount],
})
}
}
return await sendTransaction(client, {
chain: chain_,
account,
to: contract,
data,
value,
...rest,
} as SendTransactionParameters)
}

12
node_modules/viem/zksync/chainConfig.ts generated vendored Normal file
View File

@@ -0,0 +1,12 @@
import { formatters } from './formatters.js'
import { serializers } from './serializers.js'
import { getEip712Domain } from './utils/getEip712Domain.js'
export const chainConfig = {
blockTime: 1_000,
formatters,
serializers,
custom: {
getEip712Domain,
},
} as const

8
node_modules/viem/zksync/chains.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
// biome-ignore lint/performance/noBarrelFile: entrypoint module
export { zksync } from '../chains/definitions/zksync.js'
export { zksyncInMemoryNode } from '../chains/definitions/zksyncInMemoryNode.js'
export { zksyncLocalCustomHyperchain } from '../chains/definitions/zksyncLocalCustomHyperchain.js'
export { zksyncLocalHyperchain } from '../chains/definitions/zksyncLocalHyperchain.js'
export { zksyncLocalHyperchainL1 } from '../chains/definitions/zksyncLocalHyperchainL1.js'
export { zksyncLocalNode } from '../chains/definitions/zksyncLocalNode.js'
export { zksyncSepoliaTestnet } from '../chains/definitions/zksyncSepoliaTestnet.js'

4658
node_modules/viem/zksync/constants/abis.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

33
node_modules/viem/zksync/constants/address.ts generated vendored Normal file
View File

@@ -0,0 +1,33 @@
export const contractDeployerAddress =
'0x0000000000000000000000000000000000008006' as const
export const contract2FactoryAddress =
'0x0000000000000000000000000000000000010000' as const
/** The address of the L1 `ETH` token. */
export const legacyEthAddress =
'0x0000000000000000000000000000000000000000' as const
export const ethAddressInContracts =
'0x0000000000000000000000000000000000000001' as const
/** The address of the base token. */
export const l2BaseTokenAddress =
'0x000000000000000000000000000000000000800a' as const
export const l1MessengerAddress =
'0x0000000000000000000000000000000000008008' as const
export const l1ToL2AliasOffset =
'0x1111000000000000000000000000000000001111' as const
export const l2AssetRouterAddress =
'0x0000000000000000000000000000000000010003' as const
export const l2NativeTokenVaultAddress =
'0x0000000000000000000000000000000000010004' as const
export const bootloaderFormalAddress =
'0x0000000000000000000000000000000000008001' as const
export const addressModulo = 2n ** 160n

1
node_modules/viem/zksync/constants/contract.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export const accountAbstractionVersion1 = 1

5
node_modules/viem/zksync/constants/number.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import { maxUint16 } from '../../constants/number.js'
export const gasPerPubdataDefault = 50000n
export const maxBytecodeSize = maxUint16 * 32n
export const requiredL1ToL2GasPerPubdataLimit = 800n

238
node_modules/viem/zksync/decorators/eip712.ts generated vendored Normal file
View File

@@ -0,0 +1,238 @@
import type { Abi } from 'abitype'
import type { SendTransactionRequest } from '../../actions/wallet/sendTransaction.js'
import { writeContract } from '../../actions/wallet/writeContract.js'
import type { Client } from '../../clients/createClient.js'
import type { WalletActions } from '../../clients/decorators/wallet.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import {
type DeployContractParameters,
type DeployContractReturnType,
deployContract,
} from '../actions/deployContract.js'
import {
type SendTransactionParameters,
type SendTransactionReturnType,
sendTransaction,
} from '../actions/sendTransaction.js'
import {
type SignTransactionParameters,
type SignTransactionReturnType,
signTransaction,
} from '../actions/signTransaction.js'
import type { ChainEIP712 } from '../types/chain.js'
export type Eip712WalletActions<
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
> = {
/**
* Creates, signs, and sends a new transaction to the network.
*
* - Docs: https://viem.sh/docs/zksync/actions/sendTransaction
* - JSON-RPC Methods:
* - JSON-RPC Accounts: [`eth_sendTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction)
* - Local Accounts: [`eth_sendRawTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendrawtransaction)
*
* @param client - Client to use
* @param parameters - {@link SendTransactionParameters}
* @returns The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link SendTransactionReturnType}
*
* @example
* import { createWalletClient, custom } from 'viem'
* import { zksync } from 'viem/chains'
* import { eip712WalletActions } from 'viem/zksync'
*
* const client = createWalletClient({
* chain: zksync,
* transport: custom(window.ethereum),
* }).extend(eip712WalletActions())
* const hash = await client.sendTransaction({
* account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
* to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
* value: 1000000000000000000n,
* })
*
* @example
* // Account Hoisting
* import { createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { eip712WalletActions } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: zksync,
* transport: http(),
* }).extend(eip712WalletActions())
* const hash = await client.sendTransaction({
* to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
* value: 1000000000000000000n,
* })
*/
sendTransaction: <
const request extends SendTransactionRequest<chain, chainOverride>,
chainOverride extends ChainEIP712 | undefined = undefined,
>(
args: SendTransactionParameters<chain, account, chainOverride, request>,
) => Promise<SendTransactionReturnType>
/**
* Signs a transaction.
*
* - Docs: https://viem.sh/docs/actions/wallet/signTransaction
* - JSON-RPC Methods:
* - JSON-RPC Accounts: [`eth_signTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)
* - Local Accounts: Signs locally. No JSON-RPC request.
*
* @param args - {@link SignTransactionParameters}
* @returns The signed serialized transaction. {@link SignTransactionReturnType}
*
* @example
* import { createWalletClient, custom } from 'viem'
* import { zksync } from 'viem/chains'
* import { eip712WalletActions } from 'viem/zksync'
*
* const client = createWalletClient({
* chain: zksync,
* transport: custom(window.ethereum),
* }).extend(eip712WalletActions())
* const signature = await client.signTransaction({
* account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
* to: '0x0000000000000000000000000000000000000000',
* value: 1n,
* })
*
* @example
* // Account Hoisting
* import { createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { eip712WalletActions } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: zksync,
* transport: custom(window.ethereum),
* }).extend(eip712WalletActions())
* const signature = await client.signTransaction({
* to: '0x0000000000000000000000000000000000000000',
* value: 1n,
* })
*/
signTransaction: <chainOverride extends ChainEIP712 | undefined = undefined>(
args: SignTransactionParameters<chain, account, chainOverride>,
) => Promise<SignTransactionReturnType>
/**
* Deploys a contract to the network, given bytecode and constructor arguments using EIP712 transaction.
*
* - Docs: https://viem.sh/docs/contract/deployContract
* - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_deploying-contracts
*
* @param args - {@link DeployContractParameters}
* @returns The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link DeployContractReturnType}
*
* @example
* import { createWalletClient, custom } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { deployContract } from 'viem/contract'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: zksync,
* transport: custom(provider),
* })
* const hash = await client.deployContract(client, {
* abi: [],
* account: '0x…,
* deploymentType: 'create',
* bytecode: '0x608060405260405161083e38038061083e833981016040819052610...',
* factoryDeps: ['0x608060405260405161083e38038061083e833981016040819052610...'],
* gasPerPubdata: 50000n
* })
*/
deployContract: <
const abi extends Abi | readonly unknown[],
chainOverride extends ChainEIP712 | undefined,
>(
args: DeployContractParameters<
abi,
ChainEIP712 | undefined,
Account | undefined,
chainOverride
>,
) => Promise<DeployContractReturnType>
/**
* Executes a write function on a contract.
*
* - Docs: https://viem.sh/docs/contract/writeContract
* - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts
*
* A "write" function on a Solidity contract modifies the state of the blockchain. These types of functions require gas to be executed, and hence a [Transaction](https://viem.sh/docs/glossary/terms) is needed to be broadcast in order to change the state.
*
* Internally, uses a [Wallet Client](https://viem.sh/docs/clients/wallet) to call the [`sendTransaction` action](https://viem.sh/docs/actions/wallet/sendTransaction) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).
*
* __Warning: The `write` internally sends a transaction it does not validate if the contract write will succeed (the contract may throw an error). It is highly recommended to [simulate the contract write with `contract.simulate`](https://viem.sh/docs/contract/writeContract#usage) before you execute it.__
*
* @param client - Client to use
* @param parameters - {@link WriteContractParameters}
* @returns A [Transaction Hash](https://viem.sh/docs/glossary/terms#hash). {@link WriteContractReturnType}
*
* @example
* import { createWalletClient, custom, parseAbi } from 'viem'
* import { zksync } from 'viem/chains'
* import { eip712WalletActions } from 'viem/zksync'
*
* const client = createWalletClient({
* chain: zksync,
* transport: custom(window.ethereum),
* }).extend(eip712WalletActions())
* const hash = await client.writeContract({
* address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
* abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),
* functionName: 'mint',
* args: [69420],
* })
*
* @example
* // With Validation
* import { createWalletClient, http, parseAbi } from 'viem'
* import { zksync } from 'viem/chains'
* import { eip712WalletActions } from 'viem/zksync'
*
* const client = createWalletClient({
* chain: zksync,
* transport: http(),
* }).extend(eip712WalletActions())
* const { request } = await client.simulateContract({
* address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
* abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),
* functionName: 'mint',
* args: [69420],
* }
* const hash = await client.writeContract(request)
*/
writeContract: WalletActions<chain, account>['writeContract']
}
export function eip712WalletActions() {
return <
transport extends Transport,
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
>(
client: Client<transport, chain, account>,
): Eip712WalletActions<chain, account> => ({
sendTransaction: (args) => sendTransaction(client, args),
signTransaction: (args) => signTransaction(client, args),
deployContract: (args) => deployContract(client, args),
writeContract: (args) =>
writeContract(
Object.assign(client, {
sendTransaction: (args: any) => sendTransaction(client, args),
}),
args,
),
})
}

216
node_modules/viem/zksync/decorators/publicL1.ts generated vendored Normal file
View File

@@ -0,0 +1,216 @@
import type { Chain } from '../../chains/index.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import {
type GetL1AllowanceParameters,
type GetL1AllowanceReturnType,
getL1Allowance,
} from '../actions/getL1Allowance.js'
import {
type GetL1BalanceParameters,
type GetL1BalanceReturnType,
getL1Balance,
} from '../actions/getL1Balance.js'
import {
type GetL1TokenBalanceParameters,
type GetL1TokenBalanceReturnType,
getL1TokenBalance,
} from '../actions/getL1TokenBalance.js'
import {
type IsWithdrawalFinalizedParameters,
type IsWithdrawalFinalizedReturnType,
isWithdrawalFinalized,
} from '../actions/isWithdrawalFinalized.js'
export type PublicActionsL1<
account extends Account | undefined = Account | undefined,
> = {
/**
* Returns the amount of approved tokens for a specific L1 bridge.
*
* - Docs: https://viem.sh/zksync/actions/getL1Allowance
*
* @param client - Client to use
* @param parameters - {@link AllowanceL1Parameters}
* @returns The amount of approved tokens for a specific L1 bridge. {@link GetL1AllowanceReturnType}
*
* @example
* import { createPublicClient, custom, parseEther } from 'viem'
* import { base, mainnet } from 'viem/chains'
* import { publicActionsL1 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: mainnet,
* transport: custom(window.ethereum),
* }).extend(publicActionsL1())
*
* const data = await client.getL1Allowance({
* account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
* token: '0x5C221E77624690fff6dd741493D735a17716c26B'
* bridgeAddress: '0x84DbCC0B82124bee38e3Ce9a92CdE2f943bab60D',
* })
*
* @example
* // Account Hoisting
* import { createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { base, mainnet } from 'viem/chains'
* import { publicActionsL1 } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: mainnet,
* transport: http(),
* }).extend(publicActionsL1())
*
* const data = await client.getL1Allowance({
* token: '0x5C221E77624690fff6dd741493D735a17716c26B'
* bridgeAddress: '0x84DbCC0B82124bee38e3Ce9a92CdE2f943bab60D',
* })
*/
getL1Allowance: (
parameters: GetL1AllowanceParameters<account>,
) => Promise<GetL1AllowanceReturnType>
/**
* Returns the amount of the ERC20 token the client has on specific address.
*
* - Docs: https://viem.sh/zksync/actions/getL1TokenBalance
*
* @param client - Client to use
* @param parameters - {@link GetL1TokenBalanceParameters}
* @returns The amount of the ERC20 token the client has on specific address. {@link GetL1TokenBalanceReturnType}
*
* @example
* import { createPublicClient, custom, parseEther } from 'viem'
* import { base, mainnet } from 'viem/chains'
* import { publicActionsL1 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: mainnet,
* transport: custom(window.ethereum),
* }).extend(publicActionsL1())
*
* const data = await client.getL1TokenBalance({
* account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
* token: '0x5C221E77624690fff6dd741493D735a17716c26B'
* })
*
* @example
* // Account Hoisting
* import { createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { base, mainnet } from 'viem/chains'
* import { publicActionsL1 } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: mainnet,
* transport: http(),
* }).extend(publicActionsL1())
*
* const data = await client.getL1TokenBalance({
* token: '0x5C221E77624690fff6dd741493D735a17716c26B'
* })
*/
getL1TokenBalance: (
parameters: GetL1TokenBalanceParameters<account>,
) => Promise<GetL1TokenBalanceReturnType>
/**
* Returns the amount of the token held by the account on the L1 network.
*
* - Docs: https://viem.sh/zksync/actions/getL1TokenBalance
*
* @param client - Client to use
* @param parameters - {@link BalanceL1Parameters}
* @returns Returns the amount of the token held by the account on the L1 network. {@link GetL1BalanceReturnType}
*
* @example
* import { createPublicClient, custom, parseEther } from 'viem'
* import { base, mainnet } from 'viem/chains'
* import { publicActionsL1 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: mainnet,
* transport: custom(window.ethereum),
* }).extend(publicActionsL1())
*
* const data = await client.getL1Balance({
* account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'
* })
*
* const data = await client.getL1Balance({
* account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
* token: '0x5C221E77624690fff6dd741493D735a17716c26B'
* })
*
* @example
* // Account Hoisting
* import { createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { base, mainnet } from 'viem/chains'
* import { publicActionsL1 } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: mainnet,
* transport: http(),
* }).extend(publicActionsL1())
*
* const data = await client.getL1Balance({})
*
* const data = await client.getL1Balance({
* token: '0x5C221E77624690fff6dd741493D735a17716c26B'
* })
*/
getL1Balance: (
...parameters: account extends undefined
? [GetL1BalanceParameters<account>]
: [GetL1BalanceParameters<account>] | []
) => Promise<GetL1BalanceReturnType>
/**
* Returns whether the withdrawal transaction is finalized on the L1 network.
*
* @param client - Client to use
* @param parameters - {@link IsWithdrawalFinalizedParameters}
* @returns bool - Whether the withdrawal transaction is finalized on the L1 network. {@link IsWithdrawalFinalizedReturnType}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { mainnet, zksync } from 'viem/chains'
* import { publicActionsL1, publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: mainnet,
* transport: http(),
* }).extend(publicActionsL1())
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await client.isWithdrawalFinalized({
* client: clientL2,
* hash: '0x...',
* })
*/
isWithdrawalFinalized: (
parameters: IsWithdrawalFinalizedParameters,
) => Promise<IsWithdrawalFinalizedReturnType>
}
export function publicActionsL1() {
return <
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
>(
client: Client<Transport, chain, account>,
): PublicActionsL1<account> => ({
getL1Allowance: (args) => getL1Allowance(client, args),
getL1TokenBalance: (args) => getL1TokenBalance(client, args),
// @ts-expect-error
getL1Balance: (args) => getL1Balance(client, args),
isWithdrawalFinalized: (args) => isWithdrawalFinalized(client, args),
})
}

531
node_modules/viem/zksync/decorators/publicL2.ts generated vendored Normal file
View File

@@ -0,0 +1,531 @@
import type { Address } from 'abitype'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type {
EstimateFeeParameters,
EstimateFeeReturnType,
} from '../actions/estimateFee.js'
import { estimateFee } from '../actions/estimateFee.js'
import {
type EstimateGasL1ToL2Parameters,
type EstimateGasL1ToL2ReturnType,
estimateGasL1ToL2,
} from '../actions/estimateGasL1ToL2.js'
import {
type GetAllBalancesParameters,
type GetAllBalancesReturnType,
getAllBalances,
} from '../actions/getAllBalances.js'
import {
type GetBaseTokenL1AddressReturnType,
getBaseTokenL1Address,
} from '../actions/getBaseTokenL1Address.js'
import {
type GetBlockDetailsParameters,
type GetBlockDetailsReturnType,
getBlockDetails,
} from '../actions/getBlockDetails.js'
import {
type GetBridgehubContractAddressReturnType,
getBridgehubContractAddress,
} from '../actions/getBridgehubContractAddress.js'
import {
type GetDefaultBridgeAddressesReturnType,
getDefaultBridgeAddresses,
} from '../actions/getDefaultBridgeAddresses.js'
import {
type GetGasPerPubdataReturnType,
getGasPerPubdata,
} from '../actions/getGasPerPubdata.js'
import {
type GetL1BatchBlockRangeParameters,
type GetL1BatchBlockRangeReturnParameters,
getL1BatchBlockRange,
} from '../actions/getL1BatchBlockRange.js'
import {
type GetL1BatchDetailsParameters,
type GetL1BatchDetailsReturnType,
getL1BatchDetails,
} from '../actions/getL1BatchDetails.js'
import {
type GetL1BatchNumberReturnType,
getL1BatchNumber,
} from '../actions/getL1BatchNumber.js'
import {
type GetL1ChainIdReturnType,
getL1ChainId,
} from '../actions/getL1ChainId.js'
import {
type GetL1TokenAddressParameters,
type GetL1TokenAddressReturnType,
getL1TokenAddress,
} from '../actions/getL1TokenAddress.js'
import {
type GetL2TokenAddressParameters,
type GetL2TokenAddressReturnType,
getL2TokenAddress,
} from '../actions/getL2TokenAddress.js'
import {
type GetLogProofParameters,
type GetLogProofReturnType,
getLogProof,
} from '../actions/getLogProof.js'
import {
type GetMainContractAddressReturnType,
getMainContractAddress,
} from '../actions/getMainContractAddress.js'
import {
type GetRawBlockTransactionsParameters,
type GetRawBlockTransactionsReturnType,
getRawBlockTransactions,
} from '../actions/getRawBlockTransactions.js'
import {
type GetTestnetPaymasterAddressReturnType,
getTestnetPaymasterAddress,
} from '../actions/getTestnetPaymasterAddress.js'
import {
type GetTransactionDetailsParameters,
type GetTransactionDetailsReturnType,
getTransactionDetails,
} from '../actions/getTransactionDetails.js'
import type { ChainEIP712 } from '../types/chain.js'
export type PublicActionsL2<
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
> = {
/**
* Returns the addresses of the default zksync Era bridge contracts on both L1 and L2.
*
* @returns The Addresses of the default zksync Era bridge contracts on both L1 and L2. {@link DefaultBridgeAddressesReturnType}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const addresses = await client.getDefaultBridgeAddresses();
*/
getDefaultBridgeAddresses: () => Promise<GetDefaultBridgeAddressesReturnType>
/**
* Returns Testnet Paymaster Address.
*
* @returns The Address. {@link Address}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const address = await client.getTestnetPaymasterAddress();
*/
getTestnetPaymasterAddress: () => Promise<GetTestnetPaymasterAddressReturnType>
/**
* Returns the Chain Id of underlying L1 network.
*
* @returns number
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const chainId = await client.getL1ChainId();
*/
getL1ChainId: () => Promise<GetL1ChainIdReturnType>
/**
* Returns the address of a Main zksync Contract.
*
* @returns The Address. {@link Address}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const address = await client.getMainContractAddress();
*/
getMainContractAddress: () => Promise<GetMainContractAddressReturnType>
/**
* @deprecated This method has been removed from the node API.
*
* Returns all known balances for a given account.
*
* @returns The balances for a given account. {@link GetAllBalancesReturnType}
* @param args - {@link GetAllBalancesParameters}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const balances = await client.getAllBalances({account: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049"});
*/
getAllBalances: (
args: GetAllBalancesParameters,
) => Promise<GetAllBalancesReturnType>
/**
* Returns data of transactions in a block.
*
* @returns data of transactions {@link RawBlockTransactions}
* @param args - {@link GetRawBlockTransactionsParameters}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const rawTx = await client.getRawBlockTransaction({number: 1});
*/
getRawBlockTransaction: (
args: GetRawBlockTransactionsParameters,
) => Promise<GetRawBlockTransactionsReturnType>
/**
* Returns additional zksync-specific information about the L2 block.
*
* @returns zksync-specific information about the L2 block {@link BaseBlockDetails}
* @param args - {@link GetBlockDetailsParameters}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const blockDetails = await client.getBlockDetails({number: 1});
*/
getBlockDetails: (
args: GetBlockDetailsParameters,
) => Promise<GetBlockDetailsReturnType>
/**
* Returns data pertaining to a given batch.
*
* @returns data pertaining to a given batch {@link BatchDetails}
* @param args - {@link GetL1BatchDetailsParameters}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const batchDetails = await client.getL1BatchDetails({number: 1});
*/
getL1BatchDetails: (
args: GetL1BatchDetailsParameters,
) => Promise<GetL1BatchDetailsReturnType>
/**
* Returns the range of blocks contained within a batch given by batch number.
*
* @returns range of blocks contained withing a batch {@link GetL1BatchBlockRangeReturnParameters}
* @param args - {@link GetL1BatchBlockRangeParameters}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const batchBlockRange = await client.getL1BatchBlockRange({number: 1});
*/
getL1BatchBlockRange: (
args: GetL1BatchBlockRangeParameters,
) => Promise<GetL1BatchBlockRangeReturnParameters>
/**
* Returns the latest L1 batch number
*
* @returns latest L1 batch number
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const latestNumber = await client.getL1BatchNumber({number: 1});
*/
getL1BatchNumber: () => Promise<GetL1BatchNumberReturnType>
/**
* Given a transaction hash, and an index of the L2 to L1 log produced within the transaction, it returns the proof for the corresponding L2 to L1 log.
*
* @returns the proof for the corresponding L2 to L1 log.
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const proof = await client.getLogProof({txHash: "0x...",index:1});
*/
getLogProof: (args: GetLogProofParameters) => Promise<GetLogProofReturnType>
/**
* Returns data from a specific transaction given by the transaction hash
*
* @returns data from a specific transaction given by the transaction hash
*
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const details = await client.getTransactionDetails({txHash: "0x..."});
*/
getTransactionDetails: (
args: GetTransactionDetailsParameters,
) => Promise<GetTransactionDetailsReturnType>
/**
* Returns an estimated Fee for requested transaction.
*
* @returns an estimated {@link Fee} for requested transaction.
* @param args - {@link EstimateFeeParameters}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const details = await client.estimateFee({transactionRequest: {...}}});
*/
estimateFee: (
args: EstimateFeeParameters<chain, account>,
) => Promise<EstimateFeeReturnType>
/**
* Returns an estimated gas for L1 to L2 execution.
*
* @returns an estimated gas.
* @param args - {@link EstimateGasL1ToL2Parameters}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const details = await client.estimateGasL1ToL2({transactionRequest: {...}}});
*/
estimateGasL1ToL2: (
args: EstimateGasL1ToL2Parameters<chain, account>,
) => Promise<EstimateGasL1ToL2ReturnType>
/**
* Returns the Bridgehub smart contract address.
*
* @returns address of the Bridgehub smart contract address.
*
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const address = await client.getBridgehubContractAddress();
*/
getBridgehubContractAddress: () => Promise<GetBridgehubContractAddressReturnType>
/**
* Returns the address of the base L1 token.
*
* @returns address of the base L1 token.
*
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const address = await client.getBaseTokenL1Address();
*/
getBaseTokenL1Address: () => Promise<GetBaseTokenL1AddressReturnType>
/**
* Returns the L2 token address equivalent for a L1 token address as they are not equal.
* ETH address is set to zero address.
*
* @remarks Only works for tokens bridged on default ZKsync Era bridges.
*
* @param args - {@link GetL2TokenAddressParameters}
* @returns The L2 token address equivalent for a L1 token address.
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksync } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const address = await client.getL2TokenAddress({token: '0x...'});
*/
getL2TokenAddress: (
args: GetL2TokenAddressParameters,
) => Promise<GetL2TokenAddressReturnType>
/**
* Returns the L1 token address equivalent for a L2 token address as they are not equal.
* ETH address is set to zero address.
*
* @remarks Only works for tokens bridged on default ZKsync Era bridges.
*
* @param args - {@link GetL1TokenAddressParameters}
* @returns The L1 token address equivalent for a L2 token address.
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksync } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const address = await client.getL1TokenAddress({token: '0x...'});
*/
getL1TokenAddress: (
args: GetL1TokenAddressParameters,
) => Promise<GetL1TokenAddressReturnType>
/**
* Returns the scaled gas per pubdata limit for the currently open batch. Available since node version 28.7.0.
*
* @returns the scaled gas per pubdata limit for the currently open batch
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksyncLocalNode } from 'viem/chains'
* import { publicActionsL2 } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksyncLocalNode,
* transport: http(),
* }).extend(publicActionsL2())
*
* const gasPerPubdata = await client.getGasPerPubdata();
*/
getGasPerPubdata: () => Promise<GetGasPerPubdataReturnType>
}
export function publicActionsL2() {
return <
transport extends Transport = Transport,
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
>(
client: Client<transport, chain, account>,
): PublicActionsL2<chain, account> => {
return {
estimateGasL1ToL2: (args) => estimateGasL1ToL2(client, args),
getDefaultBridgeAddresses: () => getDefaultBridgeAddresses(client),
getTestnetPaymasterAddress: () => getTestnetPaymasterAddress(client),
getL1ChainId: () => getL1ChainId(client),
getMainContractAddress: () => getMainContractAddress(client),
getAllBalances: (args) => getAllBalances(client, args),
getRawBlockTransaction: (args) => getRawBlockTransactions(client, args),
getBlockDetails: (args) => getBlockDetails(client, args),
getL1BatchDetails: (args) => getL1BatchDetails(client, args),
getL1BatchBlockRange: (args) => getL1BatchBlockRange(client, args),
getL1BatchNumber: () => getL1BatchNumber(client),
getLogProof: (args) => getLogProof(client, args),
getTransactionDetails: (args) => getTransactionDetails(client, args),
estimateFee: (args) => estimateFee(client, args),
getBridgehubContractAddress: () => getBridgehubContractAddress(client),
getBaseTokenL1Address: () => getBaseTokenL1Address(client),
getL2TokenAddress: (args) => getL2TokenAddress(client, args),
getL1TokenAddress: (args) => getL1TokenAddress(client, args),
getGasPerPubdata: () => getGasPerPubdata(client),
}
}
}

223
node_modules/viem/zksync/decorators/walletL1.ts generated vendored Normal file
View File

@@ -0,0 +1,223 @@
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import type { Chain } from '../../types/chain.js'
import {
type ClaimFailedDepositParameters,
type ClaimFailedDepositReturnType,
claimFailedDeposit,
} from '../actions/claimFailedDeposit.js'
import {
type DepositParameters,
type DepositReturnType,
deposit,
} from '../actions/deposit.js'
import {
type FinalizeWithdrawalParameters,
type FinalizeWithdrawalReturnType,
finalizeWithdrawal,
} from '../actions/finalizeWithdrawal.js'
import {
type RequestExecuteParameters,
type RequestExecuteReturnType,
requestExecute,
} from '../actions/requestExecute.js'
import type { ChainEIP712 } from '../types/chain.js'
export type WalletActionsL1<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = {
/**
* Withdraws funds from the initiated deposit, which failed when finalizing on L2.
* If the deposit L2 transaction has failed, it sends an L1 transaction calling `claimFailedDeposit` method of the
* L1 bridge, which results in returning L1 tokens back to the depositor.
*
* @param parameters - {@link ClaimFailedDepositParameters}
* @returns hash - The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link ClaimFailedDepositReturnType}
*
* @example
* import { createPublicClient, createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync, mainnet } from 'viem/chains'
* import { walletActionsL1, publicActionsL2 } from 'viem/zksync'
*
* const walletClient = createWalletClient({
* chain: mainnet,
* transport: http(),
* account: privateKeyToAccount('0x…'),
* }).extend(walletActionsL1())
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await walletClient.claimFailedDeposit({
* client: clientL2,
* depositHash: <L2_HASH_OF_FAILED_DEPOSIT>,
* })
*/
claimFailedDeposit: <
chainOverride extends Chain | undefined = undefined,
chainL2 extends ChainEIP712 | undefined = ChainEIP712 | undefined,
accountL2 extends Account | undefined = Account | undefined,
>(
parameters: ClaimFailedDepositParameters<
chain,
account,
chainOverride,
chainL2,
accountL2
>,
) => Promise<ClaimFailedDepositReturnType>
/**
* Transfers the specified token from the associated account on the L1 network to the target account on the L2 network.
* The token can be either ETH or any ERC20 token. For ERC20 tokens, enough approved tokens must be associated with
* the specified L1 bridge (default one or the one defined in `bridgeAddress`).
* In this case, depending on is the chain ETH-based or not `approveToken` or `approveBaseToken`
* can be enabled to perform token approval. If there are already enough approved tokens for the L1 bridge,
* token approval will be skipped.
*
* @param parameters - {@link DepositParameters}
* @returns hash - The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link DepositReturnType}
*
* @example
* import { createPublicClient, createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync, mainnet } from 'viem/chains'
* import { walletActionsL1, legacyEthAddress, publicActionsL2 } from 'viem/zksync'
*
* const walletClient = createWalletClient({
* chain: mainnet,
* transport: http(),
* account: privateKeyToAccount('0x…'),
* }).extend(walletActionsL1())
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await walletClient.deposit({
* client: clientL2,
* token: legacyEthAddress,
* to: walletClient.account.address,
* amount: 1_000_000_000_000_000_000n,
* refundRecipient: walletClient.account.address,
* })
*/
deposit: <
chainOverride extends Chain | undefined = undefined,
chainL2 extends ChainEIP712 | undefined = ChainEIP712 | undefined,
accountL2 extends Account | undefined = Account | undefined,
>(
parameters: DepositParameters<
chain,
account,
chainOverride,
chainL2,
accountL2
>,
) => Promise<DepositReturnType>
/**
* Initiates the withdrawal process which withdraws ETH or any ERC20 token
* from the associated account on L2 network to the target account on L1 network.
*
* @param parameters - {@link FinalizeWithdrawalParameters}
* @returns hash - The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link FinalizeWithdrawalReturnType}
*
* @example
* import { createPublicClient, createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { mainnet, zksync } from 'viem/chains'
* import { walletActionsL1, publicActionsL2 } from 'viem/zksync'
*
* const walletClient = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: mainnet,
* transport: http(),
* }).extend(walletActionsL1())
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await walletClient.finalizeWithdrawal({
* client: clientL2,
* hash: '0x…',
* })
*/
finalizeWithdrawal: <
chainOverride extends Chain | undefined = undefined,
chainL2 extends ChainEIP712 | undefined = ChainEIP712 | undefined,
accountL2 extends Account | undefined = Account | undefined,
>(
parameters: FinalizeWithdrawalParameters<
chain,
account,
chainOverride,
chainL2,
accountL2
>,
) => Promise<FinalizeWithdrawalReturnType>
/**
* Requests execution of a L2 transaction from L1.
*
* @param parameters - {@link RequestExecuteParameters}
* @returns hash - The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link RequestExecuteReturnType}
*
* @example
* import { createPublicClient, createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync, mainnet } from 'viem/chains'
* import { walletActionsL1, publicActionsL2 } from 'viem/zksync'
*
* const walletClient = createWalletClient({
* chain: mainnet,
* transport: http(),
* account: privateKeyToAccount('0x…'),
* }).extend(walletActionsL1())
*
* const clientL2 = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await walletClient.requestExecute({
* client: clientL2,
* contractAddress: '0x43020e6e11cef7dce8e37baa09d9a996ac722057'
* calldata: '0x',
* l2Value: 1_000_000_000_000_000_000n,
* })
*/
requestExecute: <
chainOverride extends Chain | undefined = undefined,
chainL2 extends ChainEIP712 | undefined = ChainEIP712 | undefined,
accountL2 extends Account | undefined = Account | undefined,
>(
parameters: RequestExecuteParameters<
chain,
account,
chainOverride,
chainL2,
accountL2
>,
) => Promise<RequestExecuteReturnType>
}
export function walletActionsL1() {
return <
transport extends Transport,
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
>(
client: Client<transport, chain, account>,
): WalletActionsL1<chain, account> => ({
claimFailedDeposit: (args) => claimFailedDeposit(client, args),
deposit: (args) => deposit(client, args),
finalizeWithdrawal: (args) => finalizeWithdrawal(client, args),
requestExecute: (args) => requestExecute(client, args),
})
}

95
node_modules/viem/zksync/decorators/walletL2.ts generated vendored Normal file
View File

@@ -0,0 +1,95 @@
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { Account } from '../../types/account.js'
import {
type WithdrawParameters,
type WithdrawReturnType,
withdraw,
} from '../actions/withdraw.js'
import type { ChainEIP712 } from '../types/chain.js'
export type WalletActionsL2<
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
> = {
/**
* Initiates the withdrawal process which withdraws ETH or any ERC20 token
* from the associated account on L2 network to the target account on L1 network.
*
* @param args - {@link WithdrawParameters}
* @returns hash - The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link WithdrawReturnType}
*
*
* @example
* import { createPublicClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { publicActionsL2, legacyEthAddress } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await client.withdraw({
* account: privateKeyToAccount('0x…'),
* amount: 1_000_000_000_000_000_000n,
* token: legacyEthAddress,
* })
*
* @example Account Hoisting
* import { createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { publicActionsL2, legacyEthAddress } from 'viem/zksync'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await client.withdraw({
* amount: 1_000_000_000_000_000_000n,
* token: legacyEthAddress,
* })
*
* @example Paymaster
* import { createPublicClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { zksync } from 'viem/chains'
* import { publicActionsL2, legacyEthAddress } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: zksync,
* transport: http(),
* }).extend(publicActionsL2())
*
* const hash = await client.withdraw({
* account: privateKeyToAccount('0x…'),
* amount: 1_000_000_000_000_000_000n,
* token: legacyEthAddress,
* paymaster: '0x0EEc6f45108B4b806e27B81d9002e162BD910670',
* paymasterInput: getApprovalBasedPaymasterInput({
* minAllowance: 1n,
* token: '0x2dc3685cA34163952CF4A5395b0039c00DFa851D',
* innerInput: new Uint8Array(),
* }),
* })
*/
withdraw: <chainOverride extends ChainEIP712 | undefined = undefined>(
args: WithdrawParameters<chain, account, chainOverride>,
) => Promise<WithdrawReturnType>
}
export function walletActionsL2() {
return <
transport extends Transport,
chain extends ChainEIP712 | undefined = ChainEIP712 | undefined,
account extends Account | undefined = Account | undefined,
>(
client: Client<transport, chain, account>,
): WalletActionsL2<chain, account> => ({
withdraw: (args) => withdraw(client, args),
})
}

81
node_modules/viem/zksync/errors/bridge.ts generated vendored Normal file
View File

@@ -0,0 +1,81 @@
import { BaseError } from '../../errors/base.js'
import type { Hash } from '../../types/misc.js'
export type BaseFeeHigherThanValueErrorType = BaseFeeHigherThanValueError & {
name: 'BaseFeeHigherThanValueError'
}
export class BaseFeeHigherThanValueError extends BaseError {
constructor(baseCost: bigint, value: bigint) {
super(
[
'The base cost of performing the priority operation is higher than the provided transaction value parameter.',
'',
`Base cost: ${baseCost}.`,
`Provided value: ${value}.`,
].join('\n'),
{ name: 'BaseFeeHigherThanValueError' },
)
}
}
export type TxHashNotFoundInLogsErrorType = BaseFeeHigherThanValueError & {
name: 'TxHashNotFoundInLogsError'
}
export class TxHashNotFoundInLogsError extends BaseError {
constructor() {
super('The transaction hash not found in event logs.', {
name: 'TxHashNotFoundInLogsError',
})
}
}
export type WithdrawalLogNotFoundErrorType = WithdrawalLogNotFoundError & {
name: 'WithdrawalLogNotFoundError'
}
export class WithdrawalLogNotFoundError extends BaseError {
constructor({ hash }: { hash: Hash }) {
super(
[
`Withdrawal log with hash ${hash} not found.`,
'',
'Either the withdrawal transaction is still processing or it did not finish successfully.',
].join('\n'),
{ name: 'WithdrawalLogNotFoundError' },
)
}
}
export type CannotClaimSuccessfulDepositErrorType =
CannotClaimSuccessfulDepositError & {
name: 'CannotClaimSuccessfulDepositError'
}
export class CannotClaimSuccessfulDepositError extends BaseError {
constructor({ hash }: { hash: Hash }) {
super([`Cannot claim successful deposit: ${hash}.`].join('\n'), {
name: 'CannotClaimSuccessfulDepositError',
})
}
}
export type LogProofNotFoundErrorType = LogProofNotFoundError & {
name: 'LogProofNotFoundError'
}
export class LogProofNotFoundError extends BaseError {
constructor({ hash, index }: { hash: Hash; index: number }) {
super(
[`Log proof not found for hash ${hash} and index ${index}.`].join('\n'),
{ name: 'LogProofNotFoundError' },
)
}
}
export type L2BridgeNotFoundErrorType = L2BridgeNotFoundError & {
name: 'L2BridgeNotFoundError'
}
export class L2BridgeNotFoundError extends BaseError {
constructor() {
super(['L2 bridge address not found.'].join('\n'), {
name: 'L2BridgeNotFoundError',
})
}
}

46
node_modules/viem/zksync/errors/bytecode.ts generated vendored Normal file
View File

@@ -0,0 +1,46 @@
import { BaseError } from '../../errors/base.js'
export type BytecodeLengthExceedsMaxSizeErrorType =
BytecodeLengthExceedsMaxSizeError & {
name: 'BytecodeLengthExceedsMaxSizeError'
}
export class BytecodeLengthExceedsMaxSizeError extends BaseError {
constructor({
givenLength,
maxBytecodeSize,
}: { givenLength: number; maxBytecodeSize: bigint }) {
super(
`Bytecode cannot be longer than ${maxBytecodeSize} bytes. Given length: ${givenLength}`,
{ name: 'BytecodeLengthExceedsMaxSizeError' },
)
}
}
export type BytecodeLengthInWordsMustBeOddErrorType =
BytecodeLengthInWordsMustBeOddError & {
name: 'BytecodeLengthInWordsMustBeOddError'
}
export class BytecodeLengthInWordsMustBeOddError extends BaseError {
constructor({ givenLengthInWords }: { givenLengthInWords: number }) {
super(
`Bytecode length in 32-byte words must be odd. Given length in words: ${givenLengthInWords}`,
{ name: 'BytecodeLengthInWordsMustBeOddError' },
)
}
}
export type BytecodeLengthMustBeDivisibleBy32ErrorType =
BytecodeLengthMustBeDivisibleBy32Error & {
name: 'BytecodeLengthMustBeDivisibleBy32Error'
}
export class BytecodeLengthMustBeDivisibleBy32Error extends BaseError {
constructor({ givenLength }: { givenLength: number }) {
super(
`The bytecode length in bytes must be divisible by 32. Given length: ${givenLength}`,
{ name: 'BytecodeLengthMustBeDivisibleBy32Error' },
)
}
}

15
node_modules/viem/zksync/errors/token-is-eth.ts generated vendored Normal file
View File

@@ -0,0 +1,15 @@
import { BaseError } from '../../errors/base.js'
export type TokenIsEthErrorType = TokenIsEthError & {
name: 'TokenIsEthError'
}
export class TokenIsEthError extends BaseError {
constructor() {
super(
['Token is an ETH token.', '', 'ETH token cannot be retrieved.'].join(
'\n',
),
{ name: 'TokenIsEthError' },
)
}
}

20
node_modules/viem/zksync/errors/transaction.ts generated vendored Normal file
View File

@@ -0,0 +1,20 @@
import { BaseError } from '../../errors/base.js'
export type InvalidEip712TransactionErrorType =
InvalidEip712TransactionError & {
name: 'InvalidEip712TransactionError'
}
export class InvalidEip712TransactionError extends BaseError {
constructor() {
super(
[
'Transaction is not an EIP712 transaction.',
'',
'Transaction must:',
' - include `type: "eip712"`',
' - include one of the following: `customSignature`, `paymaster`, `paymasterInput`, `gasPerPubdata`, `factoryDeps`',
].join('\n'),
{ name: 'InvalidEip712TransactionError' },
)
}
}

146
node_modules/viem/zksync/formatters.ts generated vendored Normal file
View File

@@ -0,0 +1,146 @@
import type { ChainFormatters } from '../types/chain.js'
import { hexToBigInt, hexToNumber } from '../utils/encoding/fromHex.js'
import { hexToBytes } from '../utils/encoding/toBytes.js'
import { toHex } from '../utils/encoding/toHex.js'
import { defineBlock } from '../utils/formatters/block.js'
import { formatLog } from '../utils/formatters/log.js'
import { defineTransaction } from '../utils/formatters/transaction.js'
import { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js'
import { defineTransactionRequest } from '../utils/formatters/transactionRequest.js'
import { gasPerPubdataDefault } from './constants/number.js'
import type { ZksyncBlock, ZksyncRpcBlock } from './types/block.js'
import type { ZksyncL2ToL1Log, ZksyncLog } from './types/log.js'
import type {
ZksyncRpcTransaction,
ZksyncRpcTransactionReceipt,
ZksyncRpcTransactionRequest,
ZksyncTransaction,
ZksyncTransactionReceipt,
ZksyncTransactionRequest,
} from './types/transaction.js'
export const formatters = {
block: /*#__PURE__*/ defineBlock({
format(args: ZksyncRpcBlock): ZksyncBlock {
const transactions = args.transactions?.map((transaction) => {
if (typeof transaction === 'string') return transaction
const formatted = formatters.transaction?.format(
transaction as ZksyncRpcTransaction,
) as ZksyncTransaction
if (formatted.typeHex === '0x71') formatted.type = 'eip712'
else if (formatted.typeHex === '0xff') formatted.type = 'priority'
return formatted
})
return {
l1BatchNumber: args.l1BatchNumber
? hexToBigInt(args.l1BatchNumber)
: null,
l1BatchTimestamp: args.l1BatchTimestamp
? hexToBigInt(args.l1BatchTimestamp)
: null,
transactions,
} as ZksyncBlock
},
}),
transaction: /*#__PURE__*/ defineTransaction({
format(args: ZksyncRpcTransaction): ZksyncTransaction {
const transaction = {} as ZksyncTransaction
if (args.type === '0x71') transaction.type = 'eip712'
else if (args.type === '0xff') transaction.type = 'priority'
return {
...transaction,
l1BatchNumber: args.l1BatchNumber
? hexToBigInt(args.l1BatchNumber)
: null,
l1BatchTxIndex: args.l1BatchTxIndex
? hexToBigInt(args.l1BatchTxIndex)
: null,
} as ZksyncTransaction
},
}),
transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({
format(args: ZksyncRpcTransactionReceipt): ZksyncTransactionReceipt {
return {
l1BatchNumber: args.l1BatchNumber
? hexToBigInt(args.l1BatchNumber)
: null,
l1BatchTxIndex: args.l1BatchTxIndex
? hexToBigInt(args.l1BatchTxIndex)
: null,
logs: args.logs.map((log) => {
return {
...formatLog(log),
l1BatchNumber: log.l1BatchNumber
? hexToBigInt(log.l1BatchNumber)
: null,
transactionLogIndex: hexToNumber(log.transactionLogIndex),
logType: log.logType,
}
}) as ZksyncLog[],
l2ToL1Logs: args.l2ToL1Logs.map((l2ToL1Log) => {
return {
blockNumber: hexToBigInt(l2ToL1Log.blockHash),
blockHash: l2ToL1Log.blockHash,
l1BatchNumber: l2ToL1Log.l1BatchNumber
? hexToBigInt(l2ToL1Log.l1BatchNumber)
: null,
transactionIndex: hexToBigInt(l2ToL1Log.transactionIndex),
shardId: hexToBigInt(l2ToL1Log.shardId),
isService: l2ToL1Log.isService,
sender: l2ToL1Log.sender,
key: l2ToL1Log.key,
value: l2ToL1Log.value,
transactionHash: l2ToL1Log.transactionHash,
logIndex: hexToBigInt(l2ToL1Log.logIndex),
}
}) as ZksyncL2ToL1Log[],
} as ZksyncTransactionReceipt
},
}),
transactionRequest: /*#__PURE__*/ defineTransactionRequest({
exclude: [
'customSignature',
'factoryDeps',
'gasPerPubdata',
'paymaster',
'paymasterInput',
],
format(args: ZksyncTransactionRequest): ZksyncRpcTransactionRequest {
if (
args.gasPerPubdata ||
(args.paymaster && args.paymasterInput) ||
args.factoryDeps ||
args.customSignature
)
return {
eip712Meta: {
...(args.gasPerPubdata
? { gasPerPubdata: toHex(args.gasPerPubdata) }
: { gasPerPubdata: toHex(gasPerPubdataDefault) }),
...(args.paymaster && args.paymasterInput
? {
paymasterParams: {
paymaster: args.paymaster,
paymasterInput: Array.from(hexToBytes(args.paymasterInput)),
},
}
: {}),
...(args.factoryDeps
? {
factoryDeps: args.factoryDeps.map((dep) =>
Array.from(hexToBytes(dep)),
),
}
: {}),
...(args.customSignature
? {
customSignature: Array.from(hexToBytes(args.customSignature)),
}
: {}),
},
type: '0x71',
} as unknown as ZksyncRpcTransactionRequest
return {} as ZksyncRpcTransactionRequest
},
}),
} as const satisfies ChainFormatters

355
node_modules/viem/zksync/index.ts generated vendored Normal file
View File

@@ -0,0 +1,355 @@
// biome-ignore lint/performance/noBarrelFile: entrypoint module
export {
type ToMultisigSmartAccountParameters,
toMultisigSmartAccount,
} from './accounts/toMultisigSmartAccount.js'
export {
type ToSinglesigSmartAccountParameters,
toSinglesigSmartAccount,
} from './accounts/toSinglesigSmartAccount.js'
export {
type ToSmartAccountErrorType,
type ToSmartAccountParameters,
toSmartAccount,
} from './accounts/toSmartAccount.js'
export {
type ClaimFailedDepositErrorType,
type ClaimFailedDepositParameters,
type ClaimFailedDepositReturnType,
claimFailedDeposit,
} from './actions/claimFailedDeposit.js'
export {
type DeployContractErrorType,
type DeployContractParameters,
type DeployContractReturnType,
deployContract,
} from './actions/deployContract.js'
export {
type DepositErrorType,
type DepositParameters,
type DepositReturnType,
deposit,
} from './actions/deposit.js'
export {
type EstimateFeeParameters,
type EstimateFeeReturnType,
estimateFee,
} from './actions/estimateFee.js'
export {
type FinalizeWithdrawalErrorType,
type FinalizeWithdrawalParameters,
type FinalizeWithdrawalReturnType,
finalizeWithdrawal,
} from './actions/finalizeWithdrawal.js'
export {
type GetAllBalancesParameters,
type GetAllBalancesReturnType,
getAllBalances,
} from './actions/getAllBalances.js'
export {
type GetBlockDetailsParameters,
type GetBlockDetailsReturnType,
getBlockDetails,
} from './actions/getBlockDetails.js'
export { getBridgehubContractAddress } from './actions/getBridgehubContractAddress.js'
export {
type GetDefaultBridgeAddressesReturnType,
getDefaultBridgeAddresses,
} from './actions/getDefaultBridgeAddresses.js'
export {
type GetGasPerPubdataReturnType,
getGasPerPubdata,
} from './actions/getGasPerPubdata.js'
export {
type GetL1AllowanceErrorType,
type GetL1AllowanceParameters,
type GetL1AllowanceReturnType,
getL1Allowance,
} from './actions/getL1Allowance.js'
export {
type GetL1BalanceErrorType,
type GetL1BalanceParameters,
type GetL1BalanceReturnType,
getL1Balance,
} from './actions/getL1Balance.js'
export {
type GetL1BatchBlockRangeParameters,
type GetL1BatchBlockRangeReturnParameters,
getL1BatchBlockRange,
} from './actions/getL1BatchBlockRange.js'
export {
type GetL1BatchDetailsParameters,
type GetL1BatchDetailsReturnType,
getL1BatchDetails,
} from './actions/getL1BatchDetails.js'
export { getL1BatchNumber } from './actions/getL1BatchNumber.js'
export { getL1ChainId } from './actions/getL1ChainId.js'
export {
type GetL1TokenAddressParameters,
type GetL1TokenAddressReturnType,
getL1TokenAddress,
} from './actions/getL1TokenAddress.js'
export {
type GetL1TokenBalanceErrorType,
type GetL1TokenBalanceParameters,
type GetL1TokenBalanceReturnType,
getL1TokenBalance,
} from './actions/getL1TokenBalance.js'
export {
type GetL2TokenAddressParameters,
type GetL2TokenAddressReturnType,
getL2TokenAddress,
} from './actions/getL2TokenAddress.js'
export {
type GetLogProofParameters,
type GetLogProofReturnType,
getLogProof,
} from './actions/getLogProof.js'
export { getMainContractAddress } from './actions/getMainContractAddress.js'
export {
type GetRawBlockTransactionsParameters,
type GetRawBlockTransactionsReturnType,
getRawBlockTransactions,
} from './actions/getRawBlockTransactions.js'
export { getTestnetPaymasterAddress } from './actions/getTestnetPaymasterAddress.js'
export {
type GetTransactionDetailsParameters,
type GetTransactionDetailsReturnType,
getTransactionDetails,
} from './actions/getTransactionDetails.js'
export {
type IsWithdrawalFinalizedErrorType,
type IsWithdrawalFinalizedParameters,
type IsWithdrawalFinalizedReturnType,
isWithdrawalFinalized,
} from './actions/isWithdrawalFinalized.js'
export {
type RequestExecuteErrorType,
type RequestExecuteParameters,
type RequestExecuteReturnType,
requestExecute,
} from './actions/requestExecute.js'
export {
type SendEip712TransactionErrorType,
type SendEip712TransactionParameters,
type SendEip712TransactionReturnType,
sendEip712Transaction,
} from './actions/sendEip712Transaction.js'
export {
type SendTransactionErrorType,
type SendTransactionParameters,
type SendTransactionReturnType,
sendTransaction,
} from './actions/sendTransaction.js'
export {
type SignEip712TransactionErrorType,
type SignEip712TransactionParameters,
type SignEip712TransactionReturnType,
signEip712Transaction,
} from './actions/signEip712Transaction.js'
export {
type SignTransactionErrorType,
type SignTransactionParameters,
type SignTransactionReturnType,
signTransaction,
} from './actions/signTransaction.js'
export {
type WithdrawErrorType,
type WithdrawParameters,
type WithdrawReturnType,
withdraw,
} from './actions/withdraw.js'
export { chainConfig } from './chainConfig.js'
export {
/** @deprecated Use `zksync` instead */
zksync as zkSync,
zksync,
/** @deprecated Use `zksync` instead */
zksyncInMemoryNode as zkSyncInMemoryNode,
zksyncInMemoryNode,
zksyncLocalCustomHyperchain,
zksyncLocalHyperchain,
zksyncLocalHyperchainL1,
/** @deprecated Use `zksync` instead */
zksyncLocalNode as zkSyncLocalNode,
zksyncLocalNode,
/** @deprecated Use `zksync` instead */
zksyncSepoliaTestnet as zkSyncSepoliaTestnet,
zksyncSepoliaTestnet,
} from './chains.js'
export {
l2BaseTokenAddress,
legacyEthAddress,
} from './constants/address.js'
export {
type Eip712WalletActions,
eip712WalletActions,
} from './decorators/eip712.js'
export {
type PublicActionsL1,
publicActionsL1,
} from './decorators/publicL1.js'
export {
type PublicActionsL2,
publicActionsL2,
} from './decorators/publicL2.js'
export {
type WalletActionsL1,
walletActionsL1,
} from './decorators/walletL1.js'
export {
type WalletActionsL2,
walletActionsL2,
} from './decorators/walletL2.js'
export { serializeTransaction } from './serializers.js'
export type { ZksyncSmartAccount } from './types/account.js'
export type {
ZksyncBatchDetails,
/** @deprecated Use `ZksyncBlock` instead */
ZksyncBlock as ZkSyncBlock,
ZksyncBlock,
ZksyncBlockDetails,
ZksyncNumberParameter,
/** @deprecated Use `ZksyncRpcBlock` instead */
ZksyncRpcBlock as ZkSyncRpcBlock,
ZksyncRpcBlock,
} from './types/block.js'
export type { ChainEIP712 } from './types/chain.js'
export type {
EIP712Domain,
EIP712DomainFn,
/** @deprecated Use `ZksyncEip712Meta` instead */
ZksyncEip712Meta as ZkSyncEip712Meta,
ZksyncEip712Meta,
} from './types/eip712.js'
export type {
CommonDataRawBlockTransaction,
PublicZksyncRpcSchema,
/** @deprecated Use `PublicZksyncRpcSchema` instead */
PublicZksyncRpcSchema as PublicZkSyncRpcSchema,
RawBlockTransactions,
} from './types/eip1193.js'
export type {
/** @deprecated Use `ZksyncFeeValues` instead */
ZksyncFeeValues as ZkSyncFeeValues,
ZksyncFeeValues,
} from './types/fee.js'
export type {
/** @deprecated Use `ZksyncL2ToL1Log` instead */
ZksyncL2ToL1Log as ZkSyncL2ToL1Log,
ZksyncL2ToL1Log,
/** @deprecated Use `ZksyncLog` instead */
ZksyncLog as ZkSyncLog,
ZksyncLog,
/** @deprecated Use `ZksyncRpcL2ToL1Log` instead */
ZksyncRpcL2ToL1Log as ZkSyncRpcL2ToL1Log,
ZksyncRpcL2ToL1Log,
/** @deprecated Use `ZkSyncRpcLog` instead */
ZksyncRpcLog as ZkSyncRpcLog,
ZksyncRpcLog,
} from './types/log.js'
export type {
/** @deprecated Use `ZksyncTransactionRequest_internal` instead */
TransactionRequest as ZkSyncTransactionRequest_internal,
TransactionRequest as ZksyncTransactionRequest_internal,
TransactionRequestEIP712,
/** @deprecated Use `ZksyncEIP712TransactionSignable` instead */
ZksyncEIP712TransactionSignable as ZkSyncEIP712TransactionSignable,
ZksyncEIP712TransactionSignable,
/** @deprecated Use `ZksyncRawBlockTransactions` instead */
ZksyncRawBlockTransactions as ZkSyncRawBlockTransactions,
ZksyncRawBlockTransactions,
/** @deprecated Use `ZksyncRpcTransaction` instead */
ZksyncRpcTransaction as ZkSyncRpcTransaction,
ZksyncRpcTransaction,
/** @deprecated Use `ZksyncRpcTransactionEIP712` instead */
ZksyncRpcTransactionEIP712 as ZkSyncRpcTransactionEIP712,
ZksyncRpcTransactionEIP712,
/** @deprecated Use `ZksyncRpcTransactionPriority` instead */
ZksyncRpcTransactionPriority as ZkSyncRpcTransactionPriority,
ZksyncRpcTransactionPriority,
/** @deprecated Use `ZksyncRpcTransactionReceipt` instead */
ZksyncRpcTransactionReceipt as ZkSyncRpcTransactionReceipt,
ZksyncRpcTransactionReceipt,
/** @deprecated Use `ZksyncRpcTransactionReceiptOverrides` instead */
ZksyncRpcTransactionReceiptOverrides as ZkSyncRpcTransactionReceiptOverrides,
ZksyncRpcTransactionReceiptOverrides,
/** @deprecated Use `ZksyncRpcTransactionRequest` instead */
ZksyncRpcTransactionRequest as ZkSyncRpcTransactionRequest,
ZksyncRpcTransactionRequest,
/** @deprecated Use `ZksyncRpcTransactionRequestEIP712` instead */
ZksyncRpcTransactionRequestEIP712 as ZkSyncRpcTransactionRequestEIP712,
ZksyncRpcTransactionRequestEIP712,
/** @deprecated Use `ZksyncTransaction` instead */
ZksyncTransaction as ZkSyncTransaction,
ZksyncTransaction,
/** @deprecated Use `ZksyncTransactionDetails` instead */
ZksyncTransactionDetails as ZkSyncTransactionDetails,
ZksyncTransactionDetails,
/** @deprecated Use `ZksyncTransactionEIP712` instead */
ZksyncTransactionEIP712 as ZkSyncTransactionEIP712,
ZksyncTransactionEIP712,
/** @deprecated Use `ZksyncTransactionReceipt` instead */
ZksyncTransactionReceipt as ZkSyncTransactionReceipt,
ZksyncTransactionReceipt,
/** @deprecated Use `ZksyncTransactionReceiptOverrides` instead */
ZksyncTransactionReceiptOverrides as ZkSyncTransactionReceiptOverrides,
ZksyncTransactionReceiptOverrides,
/** @deprecated Use `ZksyncTransactionRequest` instead */
ZksyncTransactionRequest as ZkSyncTransactionRequest,
ZksyncTransactionRequest,
/** @deprecated Use `ZksyncTransactionRequestEIP712` instead */
ZksyncTransactionRequestEIP712 as ZkSyncTransactionRequestEIP712,
ZksyncTransactionRequestEIP712,
/** @deprecated Use `ZksyncTransactionSerializable` instead */
ZksyncTransactionSerializable as ZkSyncTransactionSerializable,
ZksyncTransactionSerializable,
/** @deprecated Use `ZksyncTransactionSerializableEIP712` instead */
ZksyncTransactionSerializableEIP712 as ZkSyncTransactionSerializableEIP712,
ZksyncTransactionSerializableEIP712,
/** @deprecated Use `ZksyncTransactionSerialized` instead */
ZksyncTransactionSerialized as ZkSyncTransactionSerialized,
ZksyncTransactionSerialized,
/** @deprecated Use `ZksyncTransactionSerializedEIP712` instead */
ZksyncTransactionSerializedEIP712 as ZkSyncTransactionSerializedEIP712,
ZksyncTransactionSerializedEIP712,
/** @deprecated Use `ZksyncTransactionType` instead */
ZksyncTransactionType as ZkSyncTransactionType,
ZksyncTransactionType,
} from './types/transaction.js'
export {
type EncodeDeployDataErrorType,
type EncodeDeployDataParameters,
encodeDeployData,
} from './utils/abi/encodeDeployData.js'
export {
type GetL2HashFromPriorityOpErrorType,
getL2HashFromPriorityOp,
} from './utils/bridge/getL2HashFromPriorityOp.js'
export {
type GetWithdrawalL2ToL1LogParameters,
type GetWithdrawalL2ToL1LogReturnType,
getWithdrawalL2ToL1Log,
} from './utils/bridge/getWithdrawalL2ToL1Log.js'
export {
type GetWithdrawalLogParameters,
type GetWithdrawalLogReturnType,
getWithdrawalLog,
} from './utils/bridge/getWithdrawalLog.js'
export { undoL1ToL2Alias } from './utils/bridge/undoL1ToL2Alias.js'
export {
type HashBytecodeErrorType,
hashBytecode,
} from './utils/hashBytecode.js'
export { parseEip712Transaction } from './utils/parseEip712Transaction.js'
export {
type GetApprovalBasedPaymasterInputParameters,
type GetApprovalBasedPaymasterInputReturnType,
getApprovalBasedPaymasterInput,
} from './utils/paymaster/getApprovalBasedPaymasterInput.js'
export {
type GetGeneralPaymasterInputParameters,
type GetGeneralPaymasterInputReturnType,
getGeneralPaymasterInput,
} from './utils/paymaster/getGeneralPaymasterInput.js'

6
node_modules/viem/zksync/package.json generated vendored Normal file
View File

@@ -0,0 +1,6 @@
{
"type": "module",
"types": "../_types/zksync/index.d.ts",
"module": "../_esm/zksync/index.js",
"main": "../_cjs/zksync/index.js"
}

82
node_modules/viem/zksync/serializers.ts generated vendored Normal file
View File

@@ -0,0 +1,82 @@
import type { Signature } from '../index.js'
import type { ChainSerializers } from '../types/chain.js'
import type { TransactionSerializable } from '../types/transaction.js'
import { concatHex } from '../utils/data/concat.js'
import { toHex } from '../utils/encoding/toHex.js'
import { toRlp } from '../utils/encoding/toRlp.js'
import { serializeTransaction as serializeTransaction_ } from '../utils/transaction/serializeTransaction.js'
import { gasPerPubdataDefault } from './constants/number.js'
import type {
ZksyncTransactionSerializable,
ZksyncTransactionSerializableEIP712,
ZksyncTransactionSerializedEIP712,
} from './types/transaction.js'
import { assertEip712Transaction } from './utils/assertEip712Transaction.js'
import { isEIP712Transaction } from './utils/isEip712Transaction.js'
export function serializeTransaction(
transaction: ZksyncTransactionSerializable,
signature?: Signature | undefined,
) {
if (isEIP712Transaction(transaction))
return serializeTransactionEIP712(
transaction as ZksyncTransactionSerializableEIP712,
)
return serializeTransaction_(
transaction as TransactionSerializable,
signature,
)
}
export const serializers = {
transaction: serializeTransaction,
} as const satisfies ChainSerializers
type SerializeTransactionEIP712ReturnType = ZksyncTransactionSerializedEIP712
function serializeTransactionEIP712(
transaction: ZksyncTransactionSerializableEIP712,
): SerializeTransactionEIP712ReturnType {
const {
chainId,
gas,
nonce,
to,
from,
value,
maxFeePerGas,
maxPriorityFeePerGas,
customSignature,
factoryDeps,
paymaster,
paymasterInput,
gasPerPubdata,
data,
} = transaction
assertEip712Transaction(transaction)
const serializedTransaction = [
nonce ? toHex(nonce) : '0x',
maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',
maxFeePerGas ? toHex(maxFeePerGas) : '0x',
gas ? toHex(gas) : '0x',
to ?? '0x',
value ? toHex(value) : '0x',
data ?? '0x',
toHex(chainId),
toHex(''),
toHex(''),
toHex(chainId),
from ?? '0x',
gasPerPubdata ? toHex(gasPerPubdata) : toHex(gasPerPubdataDefault),
factoryDeps ?? [],
customSignature ?? '0x', // EIP712 signature
paymaster && paymasterInput ? [paymaster, paymasterInput] : [],
]
return concatHex([
'0x71',
toRlp(serializedTransaction),
]) as SerializeTransactionEIP712ReturnType
}

5
node_modules/viem/zksync/types/account.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import type { CustomSource, LocalAccount } from '../../accounts/types.js'
export type ZksyncSmartAccount = LocalAccount<'smartAccountZksync'> & {
sign: NonNullable<CustomSource['sign']>
}

71
node_modules/viem/zksync/types/block.ts generated vendored Normal file
View File

@@ -0,0 +1,71 @@
import type { Address } from 'abitype'
import type { Block, BlockTag } from '../../types/block.js'
import type { Hash, Hex } from '../../types/misc.js'
import type { RpcBlock } from '../../types/rpc.js'
import type { Assign } from '../../types/utils.js'
import type { ZksyncRpcTransaction, ZksyncTransaction } from './transaction.js'
export type ZksyncBatchDetails = Omit<
ZksyncBlockDetails,
'operatorAddress' | 'protocolVersion'
> & {
l1GasPrice: number
l2FairGasPrice: number
}
export type ZksyncBlock<
includeTransactions extends boolean = boolean,
blockTag extends BlockTag = BlockTag,
> = Assign<
Block<
bigint,
includeTransactions,
blockTag,
ZksyncTransaction<blockTag extends 'pending' ? true : false>
>,
{
l1BatchNumber: bigint | null
l1BatchTimestamp: bigint | null
}
>
export type ZksyncBlockDetails = {
number: number
timestamp: number
l1BatchNumber: number
l1TxCount: number
l2TxCount: number
rootHash?: Hash
status: string
commitTxHash?: Hash
committedAt?: Date
proveTxHash?: Hash
provenAt?: Date
executeTxHash?: Hash
executedAt?: Date
baseSystemContractsHashes: {
bootloader: Hash
default_aa: Hash
}
operatorAddress: Address
protocolVersion?: string
}
export type ZksyncRpcBlock<
blockTag extends BlockTag = BlockTag,
includeTransactions extends boolean = boolean,
> = Assign<
RpcBlock<
blockTag,
includeTransactions,
ZksyncRpcTransaction<blockTag extends 'pending' ? true : false>
>,
{
l1BatchNumber: Hex | null
l1BatchTimestamp: Hex | null
}
>
export type ZksyncNumberParameter = {
number: number
}

28
node_modules/viem/zksync/types/chain.ts generated vendored Normal file
View File

@@ -0,0 +1,28 @@
import type {
Chain,
ChainFormatter,
ChainFormatters,
} from '../../types/chain.js'
import type { EIP712DomainFn } from './eip712.js'
import type { ZksyncTransactionSerializable } from './transaction.js'
export type ChainEIP712<
formatters extends ChainFormatters | undefined = ChainFormatters | undefined,
TransactionSignable = {},
///
transactionSerializable extends
ZksyncTransactionSerializable = formatters extends ChainFormatters
? formatters['transactionRequest'] extends ChainFormatter
? ZksyncTransactionSerializable &
Parameters<formatters['transactionRequest']['format']>[0]
: ZksyncTransactionSerializable
: ZksyncTransactionSerializable,
> = Chain<
formatters,
{
/** Return EIP712 Domain for EIP712 transaction */
getEip712Domain?:
| EIP712DomainFn<transactionSerializable, TransactionSignable>
| undefined
}
>

16
node_modules/viem/zksync/types/contract.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
import type { Address } from 'abitype'
export type BridgeContractAddresses = {
erc20L1: Address
sharedL1: Address
sharedL2: Address
l1Nullifier: Address | undefined
l1NativeTokenVault: Address | undefined
}
export type ContractDeploymentType =
| 'create'
| 'create2'
| 'createAccount'
| 'create2Account'
| undefined

168
node_modules/viem/zksync/types/eip1193.ts generated vendored Normal file
View File

@@ -0,0 +1,168 @@
import type { Address } from 'abitype'
import type { Hash, Hex } from '../../types/misc.js'
import type { ZksyncBatchDetails, ZksyncBlockDetails } from './block.js'
import type { ZksyncFee } from './fee.js'
import type { MessageProof } from './proof.js'
import type {
TransactionRequest,
ZksyncTransactionDetails,
} from './transaction.js'
export type CommonDataRawBlockTransaction = {
sender: Address
maxFeePerGas: Hex
gasLimit: Hex
gasPerPubdataLimit: Hex
ethHash: Hash
ethBlock: number
canonicalTxHash: Hash
toMint: Hex
refundRecipient: Address
}
export type RawBlockTransactions = {
common_data: {
L1?:
| ({
serialId: number
deadlineBlock: number
layer2TipFee: Hex
fullFee: Hex
opProcessingType: string
priorityQueueType: string
} & CommonDataRawBlockTransaction)
| undefined
L2?:
| {
nonce: number
fee: ZksyncFee<Hex>
initiatorAddress: Address
signature: Uint8Array
transactionType: string
input?: {
hash: Hash
data: Uint8Array
}
paymasterParams: {
paymaster: Address
paymasterInput: Uint8Array
}
}
| undefined
ProtocolUpgrade?:
| ({
upgradeId: string
} & CommonDataRawBlockTransaction)
| undefined
}
execute: {
calldata: Hash
contractAddress: Address
factoryDeps?: Hash
value: bigint
}
received_timestamp_ms: number
raw_bytes?: string
}[]
export type PublicZksyncRpcSchema = [
{
Method: 'zks_estimateFee'
Parameters: [TransactionRequest]
ReturnType: {
gas_limit: Hex
gas_per_pubdata_limit: Hex
max_fee_per_gas: Hex
max_priority_fee_per_gas: Hex
}
},
{
Method: 'zks_estimateGasL1ToL2'
Parameters: [TransactionRequest]
ReturnType: bigint
},
{
Method: 'zks_getBridgeContracts'
Parameters?: undefined
ReturnType: {
l1Erc20DefaultBridge: Address
l2Erc20DefaultBridge: Address
l1WethBridge: Address
l2WethBridge: Address
l1SharedDefaultBridge: Address
l2SharedDefaultBridge: Address
l1Nullifier?: Address
l1NativeTokenVault?: Address
}
},
{
Method: 'zks_getAllAccountBalances'
Parameters: [Address]
ReturnType: { [key: Address]: Hex }
},
{
Method: 'zks_getTestnetPaymaster'
Parameters: undefined
ReturnType: Address
},
{
Method: 'zks_L1ChainId'
Parameters: undefined
ReturnType: Hex
},
{
Method: 'zks_getMainContract'
Parameters: undefined
ReturnType: Address
},
{
Method: 'zks_L1BatchNumber'
Parameters: undefined
ReturnType: Hex
},
{
Method: 'zks_getL2ToL1LogProof'
Parameters: [Hash, number | undefined]
ReturnType: MessageProof
},
{
Method: 'zks_getL1BatchBlockRange'
Parameters: [number]
ReturnType: [Hex, Hex]
},
{
Method: 'zks_getL1BatchDetails'
Parameters: [number]
ReturnType: ZksyncBatchDetails
},
{
Method: 'zks_getRawBlockTransactions'
Parameters: [number]
ReturnType: RawBlockTransactions
},
{
Method: 'zks_getBlockDetails'
Parameters: [number]
ReturnType: ZksyncBlockDetails
},
{
Method: 'zks_getTransactionDetails'
Parameters: [Hash]
ReturnType: ZksyncTransactionDetails
},
{
Method: 'zks_getBridgehubContract'
Parameters: undefined
ReturnType: Address
},
{
Method: 'zks_getBaseTokenL1Address'
Parameters: undefined
ReturnType: Address
},
{
Method: 'zks_gasPerPubdata'
Parameters?: undefined
ReturnType: Hex
},
]

31
node_modules/viem/zksync/types/eip712.ts generated vendored Normal file
View File

@@ -0,0 +1,31 @@
import type { Address, TypedDataDomain } from 'abitype'
import type { Hex } from '../../types/misc.js'
import type { ZksyncTransactionSerializable } from './transaction.js'
type PaymasterParams = {
paymaster: Address
paymasterInput: number[]
}
export type ZksyncEip712Meta = {
gasPerPubdata?: Hex | undefined
factoryDeps?: Hex[] | undefined
customSignature?: Hex | undefined
paymasterParams?: PaymasterParams | undefined
}
type EIP712FieldType = 'uint256' | 'bytes' | 'bytes32[]'
type EIP712Field = { name: string; type: EIP712FieldType }
export type EIP712Domain<transactionSignable> = {
domain: TypedDataDomain
types: Record<string, EIP712Field[]>
primaryType: string
message: transactionSignable
}
export type EIP712DomainFn<
transactionSerializable extends
ZksyncTransactionSerializable = ZksyncTransactionSerializable,
transactionSignable = {},
> = (transaction: transactionSerializable) => EIP712Domain<transactionSignable>

12
node_modules/viem/zksync/types/fee.ts generated vendored Normal file
View File

@@ -0,0 +1,12 @@
export type ZksyncFee<quantity = bigint> = {
gasLimit: quantity
gasPerPubdataLimit: quantity
maxPriorityFeePerGas: quantity
maxFeePerGas: quantity
}
export type ZksyncFeeValues<quantity = bigint> = {
gasPrice: quantity
maxFeePerGas: quantity
maxPriorityFeePerGas: quantity
}

57
node_modules/viem/zksync/types/log.ts generated vendored Normal file
View File

@@ -0,0 +1,57 @@
import type { Abi, AbiEvent } from 'abitype'
import type { Log as Log_ } from '../../types/log.js'
import type { Hex } from '../../types/misc.js'
import type { RpcLog as RpcLog_ } from '../../types/rpc.js'
export type ZksyncLog<
quantity = bigint,
index = number,
pending extends boolean = boolean,
abiEvent extends AbiEvent | undefined = undefined,
strict extends boolean | undefined = undefined,
abi extends Abi | readonly unknown[] | undefined = abiEvent extends AbiEvent
? [abiEvent]
: undefined,
eventName extends string | undefined = abiEvent extends AbiEvent
? abiEvent['name']
: undefined,
> = Log_<quantity, index, pending, abiEvent, strict, abi, eventName> & {
l1BatchNumber: quantity | null
transactionLogIndex: index
logType: Hex | null
}
export type ZksyncRpcLog = RpcLog_ & {
l1BatchNumber: Hex | null
// These are returned but doesn't appear in Log structure neither is mentioned in https://era.zksync.io/docs/api/js/types
transactionLogIndex: Hex
logType: Hex | null
}
export type ZksyncL2ToL1Log = {
blockNumber: bigint
blockHash: string
l1BatchNumber: bigint
transactionIndex: bigint
shardId: bigint
isService: boolean
sender: string
key: string
value: string
transactionHash: string
logIndex: bigint
}
export type ZksyncRpcL2ToL1Log = {
blockNumber: Hex
blockHash: Hex
l1BatchNumber: Hex | null
transactionIndex: Hex
shardId: Hex
isService: boolean
sender: Hex
key: Hex
value: Hex
transactionHash: Hex
logIndex: Hex
}

7
node_modules/viem/zksync/types/proof.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import type { Hash } from '../../types/misc.js'
export type MessageProof = {
id: number
proof: Hash[]
root: Hash
}

322
node_modules/viem/zksync/types/transaction.ts generated vendored Normal file
View File

@@ -0,0 +1,322 @@
import type { Address } from 'abitype'
import type { FeeValuesEIP1559 } from '../../types/fee.js'
import type { Hash, Hex } from '../../types/misc.js'
import type {
Index,
Quantity,
RpcTransactionReceipt,
RpcTransactionRequest as RpcTransactionRequest_,
} from '../../types/rpc.js'
import type {
Transaction as Transaction_,
TransactionBase,
TransactionEIP1559 as TransactionEIP1559_,
TransactionEIP2930 as TransactionEIP2930_,
TransactionLegacy as TransactionLegacy_,
TransactionReceipt,
TransactionRequest as TransactionRequest_,
TransactionRequestBase,
TransactionSerializable,
TransactionSerializableEIP1559,
TransactionSerialized,
TransactionType,
} from '../../types/transaction.js'
import type { ExactPartial, OneOf, UnionOmit } from '../../types/utils.js'
import type { ZksyncEip712Meta } from './eip712.js'
import type { ZksyncFee, ZksyncFeeValues } from './fee.js'
import type {
ZksyncL2ToL1Log,
ZksyncLog,
ZksyncRpcL2ToL1Log,
ZksyncRpcLog,
} from './log.js'
type EIP712Type = '0x71'
type PriorityType = '0xff'
// Transaction
// https://era.zksync.io/docs/api/js/types#transactionresponse
type TransactionOverrides = {
l1BatchNumber: bigint | null
l1BatchTxIndex: bigint | null
}
type TransactionPriority<pending extends boolean = boolean> = TransactionBase<
bigint,
number,
pending
> &
TransactionOverrides &
FeeValuesEIP1559 & {
type: 'priority'
}
export type ZksyncTransactionEIP712<pending extends boolean = boolean> =
TransactionBase<bigint, number, pending> &
TransactionOverrides &
FeeValuesEIP1559 & {
type: 'eip712' | 'priority'
}
type Transaction<pending extends boolean = boolean> = Transaction_<
bigint,
number,
pending
> &
TransactionOverrides
export type ZksyncTransaction<pending extends boolean = boolean> =
| Transaction<pending>
| TransactionPriority<pending>
| ZksyncTransactionEIP712<pending>
// Transaction (RPC)
type RpcTransactionOverrides = {
l1BatchNumber: Hex | null
l1BatchTxIndex: Hex | null
}
type RpcTransactionLegacy<pending extends boolean = boolean> =
TransactionLegacy_<Hex, Hex, pending, '0x0'> & RpcTransactionOverrides
type RpcTransactionEIP2930<pending extends boolean = boolean> =
TransactionEIP2930_<Hex, Hex, pending, '0x1'> & RpcTransactionOverrides
type RpcTransactionEIP1559<pending extends boolean = boolean> =
TransactionEIP1559_<Hex, Hex, pending, '0x2'> & RpcTransactionOverrides
export type ZksyncRpcTransactionPriority<pending extends boolean = boolean> =
TransactionBase<Quantity, Index, pending> &
ZksyncFeeValues<Quantity> &
RpcTransactionOverrides & {
accessList?: undefined
chainId: Hex
type: PriorityType
}
export type ZksyncRpcTransactionEIP712<pending extends boolean = boolean> =
TransactionBase<Quantity, Index, pending> &
ZksyncFeeValues<Quantity> &
RpcTransactionOverrides & {
accessList?: undefined
chainId: Hex
type: EIP712Type
}
export type ZksyncRpcTransaction<pending extends boolean = boolean> = UnionOmit<
| RpcTransactionLegacy<pending>
| RpcTransactionEIP2930<pending>
| RpcTransactionEIP1559<pending>
| ZksyncRpcTransactionPriority<pending>
| ZksyncRpcTransactionEIP712<pending>,
'typeHex'
>
// Transaction Request
// https://era.zksync.io/docs/reference/concepts/transactions
export type TransactionRequest<
quantity = bigint,
index = number,
> = TransactionRequest_<quantity, index> & {
gasPerPubdata?: undefined
customSignature?: undefined
paymaster?: undefined
paymasterInput?: undefined
factoryDeps?: undefined
}
export type ZksyncTransactionRequestEIP712<
quantity = bigint,
index = number,
> = Omit<TransactionRequestBase<quantity, index>, 'type'> &
ExactPartial<FeeValuesEIP1559> & {
gasPerPubdata?: bigint | undefined
customSignature?: Hex | undefined
factoryDeps?: Hex[] | undefined
type?: 'eip712' | 'priority' | undefined
} & (
| { paymaster: Address; paymasterInput: Hex }
| { paymaster?: undefined; paymasterInput?: undefined }
)
export type ZksyncTransactionRequest<quantity = bigint, index = number> =
| TransactionRequest<quantity, index>
| ZksyncTransactionRequestEIP712<quantity, index>
type RpcTransactionRequest = RpcTransactionRequest_ & { eip712Meta?: undefined }
export type ZksyncRpcTransactionRequestEIP712 = TransactionRequestBase<
Quantity,
Index
> &
ExactPartial<FeeValuesEIP1559<Quantity>> & {
eip712Meta: ZksyncEip712Meta
type: EIP712Type | PriorityType
}
export type ZksyncRpcTransactionRequest =
| RpcTransactionRequest
| ZksyncRpcTransactionRequestEIP712
export type ZksyncTransactionType = TransactionType | 'eip712' | 'priority'
// Transaction Receipt
// https://era.zksync.io/docs/api/js/types#transactionreceipt
export type ZksyncRpcTransactionReceiptOverrides = {
l1BatchNumber: Hex | null
l1BatchTxIndex: Hex | null
logs: ZksyncRpcLog[]
l2ToL1Logs: ZksyncRpcL2ToL1Log[]
root: Hex
}
export type ZksyncRpcTransactionReceipt = Omit<RpcTransactionReceipt, 'logs'> &
ZksyncRpcTransactionReceiptOverrides
export type ZksyncTransactionReceiptOverrides = {
l1BatchNumber: bigint | null
l1BatchTxIndex: bigint | null
logs: ZksyncLog[]
l2ToL1Logs: ZksyncL2ToL1Log[]
}
export type ZksyncTransactionReceipt<
status = 'success' | 'reverted',
type = ZksyncTransactionType,
> = Omit<TransactionReceipt<bigint, number, status, type>, 'logs'> &
ZksyncTransactionReceiptOverrides
// Serializers
export type ZksyncTransactionSerializable = OneOf<
TransactionSerializable | ZksyncTransactionSerializableEIP712
>
export type ZksyncTransactionSerialized<
type extends TransactionType = 'eip712',
> = type extends 'eip712'
? ZksyncTransactionSerializedEIP712
: TransactionSerialized<type>
export type ZksyncTransactionSerializedEIP712 = `0x71${string}`
export type ZksyncTransactionSerializableEIP712<
quantity = bigint,
index = number,
> = Omit<TransactionSerializableEIP1559<quantity, index>, 'type'> & {
from: Hex
gasPerPubdata?: bigint | undefined
paymaster?: Address | undefined
factoryDeps?: Hex[] | undefined
paymasterInput?: Hex | undefined
customSignature?: Hex | undefined
type?: 'eip712' | undefined
}
// EIP712 Signer
export type ZksyncEIP712TransactionSignable = {
txType: bigint
from: bigint
to: bigint
gasLimit: bigint
gasPerPubdataByteLimit: bigint
maxFeePerGas: bigint
maxPriorityFeePerGas: bigint
paymaster: bigint
nonce: bigint
value: bigint
data: Hex
factoryDeps: Hex[]
paymasterInput: Hex
}
export type TransactionRequestEIP712<
quantity = bigint,
index = number,
transactionType = 'eip712',
> = TransactionRequestBase<quantity, index> &
ExactPartial<FeeValuesEIP1559<quantity>> & {
accessList?: undefined
gasPerPubdata?: bigint | undefined
factoryDeps?: Hex[] | undefined
paymaster?: Address | undefined
paymasterInput?: Hex | undefined
customSignature?: Hex | undefined
type?: transactionType | undefined
}
type CommonDataRawBlockTransaction = {
sender: Address
maxFeePerGas: Hex
gasLimit: Hex
gasPerPubdataLimit: Hex
ethHash: Hash
ethBlock: number
canonicalTxHash: Hash
toMint: Hex
refundRecipient: Address
}
export type ZksyncRawBlockTransactions = {
commonData: {
L1?:
| ({
serialId: number
deadlineBlock: number
layer2TipFee: Hex
fullFee: Hex
opProcessingType: string
priorityQueueType: string
} & CommonDataRawBlockTransaction)
| undefined
L2?:
| {
nonce: number
fee: ZksyncFee<Hex>
initiatorAddress: Address
signature: Uint8Array
transactionType: string
input?:
| {
hash: Hash
data: Uint8Array
}
| undefined
paymasterParams: {
paymaster: Address
paymasterInput: Uint8Array
}
}
| undefined
ProtocolUpgrade?:
| ({
upgradeId: string
} & CommonDataRawBlockTransaction)
| undefined
}
execute: {
calldata: Hash
contractAddress: Address
factoryDeps?: Hash
value: bigint
}
receivedTimestampMs: number
rawBytes?: string | undefined
}[]
export type ZksyncTransactionDetails = {
isL1Originated: boolean
status: string
fee: bigint
gasPerPubdata: bigint
initiatorAddress: Address
receivedAt: Date
ethCommitTxHash?: Hash | undefined
ethProveTxHash?: Hash | undefined
ethExecuteTxHash?: Hash | undefined
}

129
node_modules/viem/zksync/utils/abi/encodeDeployData.ts generated vendored Normal file
View File

@@ -0,0 +1,129 @@
import type { Abi } from 'abitype'
import { zeroHash } from '../../../constants/bytes.js'
import {
AbiConstructorNotFoundError,
AbiConstructorParamsNotFoundError,
} from '../../../errors/abi.js'
import type { ErrorType } from '../../../errors/utils.js'
import type { ContractConstructorArgs } from '../../../types/contract.js'
import type { Hash, Hex } from '../../../types/misc.js'
import { encodeAbiParameters } from '../../../utils/abi/encodeAbiParameters.js'
import type {
EncodeDeployDataParameters as EncodeDeployDataParameters_,
EncodeDeployDataReturnType,
} from '../../../utils/abi/encodeDeployData.js'
import {
type EncodeFunctionDataErrorType,
encodeFunctionData,
} from '../../../utils/abi/encodeFunctionData.js'
import { toHex } from '../../../utils/encoding/toHex.js'
import { contractDeployerAbi } from '../../constants/abis.js'
import { accountAbstractionVersion1 } from '../../constants/contract.js'
import type { ContractDeploymentType } from '../../types/contract.js'
import { type HashBytecodeErrorType, hashBytecode } from '../hashBytecode.js'
const docsPath = '/docs/contract/encodeDeployData'
/** @internal */
export type EncodeDeployDataParameters<
abi extends Abi | readonly unknown[] = Abi,
hasConstructor = abi extends Abi
? Abi extends abi
? true
: [Extract<abi[number], { type: 'constructor' }>] extends [never]
? false
: true
: true,
allArgs = ContractConstructorArgs<abi>,
> = EncodeDeployDataParameters_<abi, hasConstructor, allArgs> & {
deploymentType?: ContractDeploymentType | undefined
salt?: Hash | undefined
}
export type EncodeDeployDataErrorType =
| EncodeFunctionDataErrorType
| HashBytecodeErrorType
| ErrorType
export function encodeDeployData<const abi extends Abi | readonly unknown[]>(
parameters: EncodeDeployDataParameters<abi>,
): EncodeDeployDataReturnType {
const { abi, args, bytecode, deploymentType, salt } =
parameters as EncodeDeployDataParameters
if (!args || args.length === 0) {
const { functionName, argsContractDeployer } = getDeploymentDetails(
deploymentType,
salt ?? zeroHash,
toHex(hashBytecode(bytecode)),
'0x',
)
return encodeFunctionData({
abi: contractDeployerAbi,
functionName,
args: argsContractDeployer,
})
}
const description = abi.find((x) => 'type' in x && x.type === 'constructor')
if (!description) throw new AbiConstructorNotFoundError({ docsPath })
if (!('inputs' in description))
throw new AbiConstructorParamsNotFoundError({ docsPath })
if (!description.inputs || description.inputs.length === 0)
throw new AbiConstructorParamsNotFoundError({ docsPath })
const data = encodeAbiParameters(description.inputs, args)
const { functionName, argsContractDeployer } = getDeploymentDetails(
deploymentType,
salt ?? zeroHash,
toHex(hashBytecode(bytecode)),
data,
)
return encodeFunctionData({
abi: contractDeployerAbi,
functionName,
args: argsContractDeployer,
})
}
function getDeploymentDetails(
deploymentType: ContractDeploymentType,
salt: Hash,
bytecodeHash: Hex,
data: Hex,
): {
functionName: string
argsContractDeployer: readonly unknown[]
} {
const contractDeploymentArgs = [salt, bytecodeHash, data]
const deploymentOptions = {
create: {
functionName: 'create',
argsContractDeployer: contractDeploymentArgs,
},
create2: {
functionName: 'create2',
argsContractDeployer: contractDeploymentArgs,
},
createAccount: {
functionName: 'createAccount',
argsContractDeployer: [
...contractDeploymentArgs,
accountAbstractionVersion1,
],
},
create2Account: {
functionName: 'create2Account',
argsContractDeployer: [
...contractDeploymentArgs,
accountAbstractionVersion1,
],
},
}
const deploymentKey = deploymentType || 'create'
return deploymentOptions[deploymentKey]
}

29
node_modules/viem/zksync/utils/assertEip712Request.ts generated vendored Normal file
View File

@@ -0,0 +1,29 @@
import type { ErrorType } from '../../errors/utils.js'
import type { ExactPartial } from '../../types/utils.js'
import {
type AssertRequestErrorType,
assertRequest,
} from '../../utils/transaction/assertRequest.js'
import type { zksync } from '../../zksync/chains.js'
import type { SendTransactionParameters } from '../actions/sendTransaction.js'
import {
InvalidEip712TransactionError,
type InvalidEip712TransactionErrorType,
} from '../errors/transaction.js'
import { isEIP712Transaction } from './isEip712Transaction.js'
export type AssertEip712RequestParameters = ExactPartial<
SendTransactionParameters<typeof zksync>
>
/** @internal */
export type AssertEip712RequestErrorType =
| InvalidEip712TransactionErrorType
| AssertRequestErrorType
| ErrorType
export function assertEip712Request(args: AssertEip712RequestParameters) {
if (!isEIP712Transaction(args as any))
throw new InvalidEip712TransactionError()
assertRequest(args as any)
}

View File

@@ -0,0 +1,36 @@
import { InvalidAddressError } from '../../errors/address.js'
import { BaseError } from '../../errors/base.js'
import { InvalidChainIdError } from '../../errors/chain.js'
import type { ExactPartial } from '../../types/utils.js'
import { isAddress } from '../../utils/address/isAddress.js'
import { InvalidEip712TransactionError } from '../errors/transaction.js'
import type {
ZksyncTransactionSerializable,
ZksyncTransactionSerializableEIP712,
} from '../types/transaction.js'
import { isEIP712Transaction } from './isEip712Transaction.js'
export function assertEip712Transaction(
transaction: ExactPartial<ZksyncTransactionSerializable>,
) {
const { chainId, to, from, paymaster, paymasterInput } =
transaction as ZksyncTransactionSerializableEIP712
if (!isEIP712Transaction(transaction))
throw new InvalidEip712TransactionError()
if (!chainId || chainId <= 0) throw new InvalidChainIdError({ chainId })
if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })
if (from && !isAddress(from)) throw new InvalidAddressError({ address: from })
if (paymaster && !isAddress(paymaster))
throw new InvalidAddressError({ address: paymaster })
if (paymaster && !paymasterInput) {
throw new BaseError(
'`paymasterInput` must be provided when `paymaster` is defined',
)
}
if (!paymaster && paymasterInput) {
throw new BaseError(
'`paymaster` must be provided when `paymasterInput` is defined',
)
}
}

View File

@@ -0,0 +1,29 @@
import type { Address } from '../../../accounts/index.js'
import { pad, toHex } from '../../../utils/index.js'
import { addressModulo, l1ToL2AliasOffset } from '../../constants/address.js'
/**
* Converts the address that submitted a transaction to the inbox on L1 to the `msg.sender` viewed on L2.
* Returns the `msg.sender` of the `L1->L2` transaction as the address of the contract that initiated the transaction.
*
* All available cases:
* - During a normal transaction, if contract `A` calls contract `B`, the `msg.sender` is `A`.
* - During `L1->L2` communication, if an EOA `X` calls contract `B`, the `msg.sender` is `X`.
* - During `L1->L2` communication, if a contract `A` calls contract `B`, the `msg.sender` is `applyL1ToL2Alias(A)`.
*
* @param address - The address of the contract.
* @returns address - The transformed address representing the `msg.sender` on L2.
*
* @example
* import { applyL1ToL2Alias } from 'viem/zksync'
*
* const l1ContractAddress = "0x702942B8205E5dEdCD3374E5f4419843adA76Eeb";
* const l2ContractAddress = utils.applyL1ToL2Alias(l1ContractAddress);
* // l2ContractAddress = "0x813A42B8205E5DedCd3374e5f4419843ADa77FFC"
*/
export function applyL1ToL2Alias(address: Address): Address {
return pad(
toHex((BigInt(address) + BigInt(l1ToL2AliasOffset)) % addressModulo),
{ size: 20 },
)
}

View File

@@ -0,0 +1,63 @@
import type { Address } from 'abitype'
import type { Hash } from '../../../types/misc.js'
import type { TransactionReceipt } from '../../../types/transaction.js'
import { decodeEventLog, isAddressEqual } from '../../../utils/index.js'
import { zksyncAbi } from '../../constants/abis.js'
import {
TxHashNotFoundInLogsError,
type TxHashNotFoundInLogsErrorType,
} from '../../errors/bridge.js'
export type GetL2HashFromPriorityOpErrorType = TxHashNotFoundInLogsErrorType
/**
* Returns the hash of the L2 priority operation from a given L1 transaction receipt.
*
* @param receipt - The L1 transaction receipt.
* @param zksync - The address of the ZKsync Era main contract.
* @returns hash - The hash of the L2 priority operation.
*
* @example
* import { createPublicClient, http } from 'viem'
* import { zksync, mainnet } from 'viem/chains'
* import { publicActionsL2, getL2HashFromPriorityOp } from 'viem/zksync'
*
* const client = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
*
* const zksyncClient = const client = createPublicClient({
* chain: zksync,
* transport: http(),
* })
*
* const receipt = await client.waitForTransactionReceipt({hash: '0x...'})
* const l2Hash = getL2HashFromPriorityOp(
* receipt,
* await zksyncClient.getMainContractAddress()
* )
*/
export function getL2HashFromPriorityOp(
receipt: TransactionReceipt,
zksync: Address,
): Address {
let hash: Hash | null = null
for (const log of receipt.logs) {
if (!isAddressEqual(log.address, zksync)) continue
try {
const priorityQueueLog = decodeEventLog({
abi: zksyncAbi,
data: log.data,
topics: log.topics,
})
if (priorityQueueLog && (priorityQueueLog.args as any).txHash !== null)
hash = (priorityQueueLog.args as any).txHash
} catch (_e) {}
}
if (!hash) {
throw new TxHashNotFoundInLogsError()
}
return hash
}

View File

@@ -0,0 +1,47 @@
import type { Address } from 'abitype'
import type { Account } from '../../../accounts/index.js'
import { getTransactionReceipt } from '../../../actions/index.js'
import type { Client } from '../../../clients/createClient.js'
import type { Transport } from '../../../clients/transports/createTransport.js'
import type { Chain } from '../../../types/chain.js'
import type { Hash } from '../../../types/misc.js'
import { isAddressEqual } from '../../../utils/index.js'
import { l1MessengerAddress } from '../../constants/address.js'
import type { ZksyncL2ToL1Log } from '../../types/log.js'
import type { ZksyncTransactionReceipt } from '../../types/transaction.js'
export type GetWithdrawalL2ToL1LogParameters = {
/** Hash of the L2 transaction where the withdrawal was initiated. */
hash: Hash
/** In case there were multiple withdrawals in one transaction, you may pass an index of the
withdrawal you want to finalize. */
index?: number | undefined
}
export type GetWithdrawalL2ToL1LogReturnType = {
l2ToL1LogIndex: number | null
l2ToL1Log: ZksyncL2ToL1Log
}
/** @internal */
export async function getWithdrawalL2ToL1Log<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: GetWithdrawalL2ToL1LogParameters,
): Promise<GetWithdrawalL2ToL1LogReturnType> {
const { hash, index = 0 } = parameters
const receipt = (await getTransactionReceipt(client, {
hash,
})) as ZksyncTransactionReceipt
const messages = Array.from(receipt.l2ToL1Logs.entries()).filter(([, log]) =>
isAddressEqual(log.sender as Address, l1MessengerAddress),
)
const [l2ToL1LogIndex, l2ToL1Log] = messages[index]
return {
l2ToL1LogIndex,
l2ToL1Log,
}
}

View File

@@ -0,0 +1,47 @@
import type { Account } from '../../../accounts/types.js'
import { getTransactionReceipt } from '../../../actions/index.js'
import type { Client } from '../../../clients/createClient.js'
import type { Transport } from '../../../clients/transports/createTransport.js'
import type { Chain } from '../../../types/chain.js'
import type { Hash } from '../../../types/misc.js'
import { isAddressEqual, toFunctionHash } from '../../../utils/index.js'
import { l1MessengerAddress } from '../../constants/address.js'
import type { ZksyncLog } from '../../types/log.js'
import type { ZksyncTransactionReceipt } from '../../types/transaction.js'
export type GetWithdrawalLogParameters = {
/** Hash of the L2 transaction where the withdrawal was initiated. */
hash: Hash
/** In case there were multiple withdrawals in one transaction, you may pass an index of the
withdrawal you want to finalize. */
index?: number | undefined
}
export type GetWithdrawalLogReturnType = {
log: ZksyncLog
l1BatchTxId: bigint | null
}
/** @internal */
export async function getWithdrawalLog<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: GetWithdrawalLogParameters,
): Promise<GetWithdrawalLogReturnType> {
const { hash, index = 0 } = parameters
const receipt = (await getTransactionReceipt(client, {
hash,
})) as ZksyncTransactionReceipt
const log = receipt.logs.filter(
(log) =>
isAddressEqual(log.address, l1MessengerAddress) &&
log.topics[0] === toFunctionHash('L1MessageSent(address,bytes32,bytes)'),
)[index]
return {
log,
l1BatchTxId: receipt.l1BatchTxIndex,
}
}

View File

@@ -0,0 +1,22 @@
import type { Address } from '../../../accounts/index.js'
import { pad, toHex } from '../../../utils/index.js'
import { addressModulo, l1ToL2AliasOffset } from '../../constants/address.js'
/**
* Converts and returns the `msg.sender` viewed on L2 to the address that submitted a transaction to the inbox on L1.
*
* @param address - The sender address viewed on L2.
* @returns address - The hash of the L2 priority operation.
*
* @example
* import { undoL1ToL2Alias } from 'viem/zksync'
*
* const l2ContractAddress = "0x813A42B8205E5DedCd3374e5f4419843ADa77FFC";
* const l1ContractAddress = utils.undoL1ToL2Alias(l2ContractAddress);
* // const l1ContractAddress = "0x702942B8205E5dEdCD3374E5f4419843adA76Eeb"
*/
export function undoL1ToL2Alias(address: Address): Address {
let result = BigInt(address) - BigInt(l1ToL2AliasOffset)
if (result < 0n) result += addressModulo
return pad(toHex(result), { size: 20 })
}

11
node_modules/viem/zksync/utils/camelCaseKeys.ts generated vendored Normal file
View File

@@ -0,0 +1,11 @@
export function camelCaseKeys(response: object): object {
if (!response) return response
if (typeof response !== 'object') return response
if (Array.isArray(response)) return response.map(camelCaseKeys)
return Object.fromEntries(
Object.entries(response).map(([key, value]) => [
key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()),
camelCaseKeys(value),
]),
)
}

86
node_modules/viem/zksync/utils/getEip712Domain.ts generated vendored Normal file
View File

@@ -0,0 +1,86 @@
import { toHex } from '../../utils/encoding/toHex.js'
import { gasPerPubdataDefault } from '../constants/number.js'
import type { EIP712DomainFn } from '../types/eip712.js'
import type {
ZksyncEIP712TransactionSignable,
ZksyncTransactionSerializable,
ZksyncTransactionSerializableEIP712,
} from '../types/transaction.js'
import { assertEip712Transaction } from './assertEip712Transaction.js'
import { hashBytecode } from './hashBytecode.js'
export const getEip712Domain: EIP712DomainFn<
ZksyncTransactionSerializable,
ZksyncEIP712TransactionSignable
> = (transaction) => {
assertEip712Transaction(transaction)
const message = transactionToMessage(
transaction as ZksyncTransactionSerializableEIP712,
)
return {
domain: {
name: 'zkSync',
version: '2',
chainId: transaction.chainId,
},
types: {
Transaction: [
{ name: 'txType', type: 'uint256' },
{ name: 'from', type: 'uint256' },
{ name: 'to', type: 'uint256' },
{ name: 'gasLimit', type: 'uint256' },
{ name: 'gasPerPubdataByteLimit', type: 'uint256' },
{ name: 'maxFeePerGas', type: 'uint256' },
{ name: 'maxPriorityFeePerGas', type: 'uint256' },
{ name: 'paymaster', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
{ name: 'value', type: 'uint256' },
{ name: 'data', type: 'bytes' },
{ name: 'factoryDeps', type: 'bytes32[]' },
{ name: 'paymasterInput', type: 'bytes' },
],
},
primaryType: 'Transaction',
message: message,
}
}
//////////////////////////////////////////////////////////////////////////////
// Utilities
function transactionToMessage(
transaction: ZksyncTransactionSerializableEIP712,
): ZksyncEIP712TransactionSignable {
const {
gas,
nonce,
to,
from,
value,
maxFeePerGas,
maxPriorityFeePerGas,
factoryDeps,
paymaster,
paymasterInput,
gasPerPubdata,
data,
} = transaction
return {
txType: 113n,
from: BigInt(from),
to: to ? BigInt(to) : 0n,
gasLimit: gas ?? 0n,
gasPerPubdataByteLimit: gasPerPubdata ?? gasPerPubdataDefault,
maxFeePerGas: maxFeePerGas ?? 0n,
maxPriorityFeePerGas: maxPriorityFeePerGas ?? 0n,
paymaster: paymaster ? BigInt(paymaster) : 0n,
nonce: nonce ? BigInt(nonce) : 0n,
value: value ?? 0n,
data: data ?? '0x',
factoryDeps: factoryDeps?.map((dep) => toHex(hashBytecode(dep))) ?? [],
paymasterInput: paymasterInput ? paymasterInput : '0x',
}
}

60
node_modules/viem/zksync/utils/hashBytecode.ts generated vendored Normal file
View File

@@ -0,0 +1,60 @@
import type { ErrorType } from '../../errors/utils.js'
import type { Hex } from '../../types/misc.js'
import { pad } from '../../utils/data/pad.js'
import { type ToBytesErrorType, toBytes } from '../../utils/encoding/toBytes.js'
import { type Sha256ErrorType, sha256 } from '../../utils/hash/sha256.js'
import { maxBytecodeSize } from '../constants/number.js'
import {
BytecodeLengthExceedsMaxSizeError,
type BytecodeLengthExceedsMaxSizeErrorType,
BytecodeLengthInWordsMustBeOddError,
type BytecodeLengthInWordsMustBeOddErrorType,
BytecodeLengthMustBeDivisibleBy32Error,
type BytecodeLengthMustBeDivisibleBy32ErrorType,
} from '../errors/bytecode.js'
export type HashBytecodeErrorType =
| BytecodeLengthExceedsMaxSizeErrorType
| BytecodeLengthInWordsMustBeOddErrorType
| BytecodeLengthMustBeDivisibleBy32ErrorType
| Sha256ErrorType
| ToBytesErrorType
| ErrorType
export function hashBytecode(bytecode: Hex): Uint8Array {
const bytecodeBytes = toBytes(bytecode)
if (bytecodeBytes.length % 32 !== 0)
throw new BytecodeLengthMustBeDivisibleBy32Error({
givenLength: bytecodeBytes.length,
})
if (bytecodeBytes.length > maxBytecodeSize)
throw new BytecodeLengthExceedsMaxSizeError({
givenLength: bytecodeBytes.length,
maxBytecodeSize,
})
const hashStr = sha256(bytecodeBytes)
const hash = toBytes(hashStr)
// Note that the length of the bytecode
// should be provided in 32-byte words.
const bytecodeLengthInWords = bytecodeBytes.length / 32
if (bytecodeLengthInWords % 2 === 0) {
throw new BytecodeLengthInWordsMustBeOddError({
givenLengthInWords: bytecodeLengthInWords,
})
}
const bytecodeLength = toBytes(bytecodeLengthInWords)
// The bytecode should always take the first 2 bytes of the bytecode hash,
// so we pad it from the left in case the length is smaller than 2 bytes.
const bytecodeLengthPadded = pad(bytecodeLength, { size: 2 })
const codeHashVersion = new Uint8Array([1, 0])
hash.set(codeHashVersion, 0)
hash.set(bytecodeLengthPadded, 2)
return hash
}

23
node_modules/viem/zksync/utils/isEip712Transaction.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import type { ExactPartial, OneOf } from '../../types/utils.js'
import type {
ZksyncTransactionRequest,
ZksyncTransactionSerializable,
} from '../types/transaction.js'
export function isEIP712Transaction(
transaction: ExactPartial<
OneOf<ZksyncTransactionRequest | ZksyncTransactionSerializable>
>,
) {
if (transaction.type === 'eip712') return true
if (
('customSignature' in transaction && transaction.customSignature) ||
('paymaster' in transaction && transaction.paymaster) ||
('paymasterInput' in transaction && transaction.paymasterInput) ||
('gasPerPubdata' in transaction &&
typeof transaction.gasPerPubdata === 'bigint') ||
('factoryDeps' in transaction && transaction.factoryDeps)
)
return true
return false
}

20
node_modules/viem/zksync/utils/isEth.ts generated vendored Normal file
View File

@@ -0,0 +1,20 @@
import type { Address } from '../../accounts/index.js'
import {
ethAddressInContracts,
l2BaseTokenAddress,
legacyEthAddress,
} from '../constants/address.js'
export function isEth(token: Address) {
return (
token.localeCompare(legacyEthAddress, undefined, {
sensitivity: 'accent',
}) === 0 ||
token.localeCompare(l2BaseTokenAddress, undefined, {
sensitivity: 'accent',
}) === 0 ||
token.localeCompare(ethAddressInContracts, undefined, {
sensitivity: 'accent',
}) === 0
)
}

View File

@@ -0,0 +1,57 @@
import { BaseError } from '../../errors/base.js'
import type { Hex } from '../../types/misc.js'
import {
fromHex,
fromRlp,
hexToBigInt,
hexToNumber,
} from '../../utils/index.js'
import type { ZksyncTransactionSerializableEIP712 } from '../types/transaction.js'
export function parseEip712Transaction(
transaction: Hex,
): ZksyncTransactionSerializableEIP712 {
const payload = fromHex(transaction, 'bytes')
if (payload[0] !== 113) throw new BaseError('transaction type must be eip712')
function validHex(value: Hex): Hex {
if (!value || value === '0x') return '0x0'
return value
}
function parsePaymasterArray(arr: Hex[]) {
if (arr.length === 0) return undefined
if (arr.length !== 2)
throw new BaseError(
`Invalid paymaster parameters, expected to have length of 2, found ${arr.length}!`,
)
return {
paymaster: arr[0],
paymasterInput: arr[1],
}
}
const raw = fromRlp(payload.slice(1)) as Hex[]
const paymasterParams = parsePaymasterArray(raw[15] as unknown as Hex[])
return {
type: 'eip712',
nonce: hexToNumber(validHex(raw[0])),
maxPriorityFeePerGas: hexToBigInt(validHex(raw[1])),
maxFeePerGas: hexToBigInt(validHex(raw[2])),
gas: hexToBigInt(validHex(raw[3])),
to: raw[4],
value: hexToBigInt(validHex(raw[5])),
data: raw[6],
v: hexToBigInt(validHex(raw[7])),
r: raw[8],
s: raw[9],
chainId: hexToNumber(validHex(raw[10])),
from: raw[11],
gasPerPubdata: hexToBigInt(validHex(raw[12])),
factoryDeps: raw[13] as unknown as Hex[],
customSignature: raw[14],
paymaster: paymasterParams?.paymaster,
paymasterInput: paymasterParams?.paymasterInput,
}
}

View File

@@ -0,0 +1,32 @@
import type { Address } from 'abitype'
import type { ByteArray, Hex } from '../../../types/misc.js'
import {
type EncodeFunctionDataReturnType,
encodeFunctionData,
} from '../../../utils/abi/encodeFunctionData.js'
import { bytesToHex } from '../../../utils/encoding/toHex.js'
import { paymasterAbi } from '../../constants/abis.js'
export type GetApprovalBasedPaymasterInputParameters = {
innerInput: Hex | ByteArray
minAllowance: bigint
token: Address
}
export type GetApprovalBasedPaymasterInputReturnType =
EncodeFunctionDataReturnType
export function getApprovalBasedPaymasterInput(
parameters: GetApprovalBasedPaymasterInputParameters,
): GetApprovalBasedPaymasterInputReturnType {
const { innerInput, minAllowance, token } = parameters
const innerInputHex =
typeof innerInput === 'string' ? innerInput : bytesToHex(innerInput)
return encodeFunctionData({
abi: paymasterAbi,
functionName: 'approvalBased',
args: [token, minAllowance, innerInputHex],
})
}

View File

@@ -0,0 +1,28 @@
import type { ByteArray, Hex } from '../../../types/misc.js'
import {
type EncodeFunctionDataReturnType,
encodeFunctionData,
} from '../../../utils/abi/encodeFunctionData.js'
import { bytesToHex } from '../../../utils/encoding/toHex.js'
import { paymasterAbi } from '../../constants/abis.js'
export type GetGeneralPaymasterInputParameters = {
innerInput: Hex | ByteArray
}
export type GetGeneralPaymasterInputReturnType = EncodeFunctionDataReturnType
export function getGeneralPaymasterInput(
parameters: GetGeneralPaymasterInputParameters,
): GetGeneralPaymasterInputReturnType {
const { innerInput } = parameters
const innerInputHex =
typeof innerInput === 'string' ? innerInput : bytesToHex(innerInput)
return encodeFunctionData({
abi: paymasterAbi,
functionName: 'general',
args: [innerInputHex],
})
}