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

2286
node_modules/viem/tempo/Abis.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

645
node_modules/viem/tempo/Account.ts generated vendored Normal file
View File

@@ -0,0 +1,645 @@
import * as Address from 'ox/Address'
import * as Hex from 'ox/Hex'
import * as P256 from 'ox/P256'
import * as PublicKey from 'ox/PublicKey'
import * as Secp256k1 from 'ox/Secp256k1'
import * as Signature from 'ox/Signature'
import { KeyAuthorization, SignatureEnvelope } from 'ox/tempo'
import * as WebAuthnP256 from 'ox/WebAuthnP256'
import * as WebCryptoP256 from 'ox/WebCryptoP256'
import type {
LocalAccount,
Account as viem_Account,
} from '../accounts/types.js'
import { parseAccount } from '../accounts/utils/parseAccount.js'
import type { TransactionSerializable } from '../types/transaction.js'
import type { OneOf, RequiredBy } from '../types/utils.js'
import { hashAuthorization } from '../utils/authorization/hashAuthorization.js'
import { keccak256 } from '../utils/hash/keccak256.js'
import { hashMessage } from '../utils/signature/hashMessage.js'
import { hashTypedData } from '../utils/signature/hashTypedData.js'
import type { SerializeTransactionFn } from '../utils/transaction/serializeTransaction.js'
import * as Transaction from './Transaction.js'
export type Account_base<source extends string = string> = RequiredBy<
LocalAccount<source>,
'sign' | 'signAuthorization' | 'signTransaction'
> & {
/** Key type. */
keyType: SignatureEnvelope.Type
/** Sign transaction fn. */
signTransaction: <
serializer extends
SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<Transaction.TransactionSerializableTempo>,
transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],
>(
transaction: transaction,
options?:
| {
serializer?: serializer | undefined
}
| undefined,
) => Promise<Hex.Hex>
}
export type RootAccount = Account_base<'root'> & {
/** Sign key authorization. */
signKeyAuthorization: (
key: resolveAccessKey.Parameters,
parameters: Pick<
KeyAuthorization.KeyAuthorization,
'chainId' | 'expiry' | 'limits' | 'scopes'
>,
) => Promise<KeyAuthorization.Signed>
}
export type AccessKeyAccount = Account_base<'accessKey'> & {
/** Access key ID. */
accessKeyAddress: Address.Address
}
export type Account = OneOf<RootAccount | AccessKeyAccount>
/** Instantiates an Account. */
export function from<const parameters extends from.Parameters>(
parameters: parameters | from.Parameters,
): from.ReturnValue<parameters> {
const { access } = parameters
if (access) return fromAccessKey(parameters) as never
return fromRoot(parameters) as never
}
export declare namespace from {
export type Parameters = OneOf<fromRoot.Parameters | fromAccessKey.Parameters>
export type ReturnValue<
parameters extends {
access?: fromAccessKey.Parameters['access'] | undefined
} = {
access?: fromAccessKey.Parameters['access'] | undefined
},
> = parameters extends {
access: fromAccessKey.Parameters['access']
}
? AccessKeyAccount
: RootAccount
}
/**
* Instantiates an Account from a headless WebAuthn credential (P256 private key).
*
* @example
* ```ts
* import { Account } from 'viem/tempo'
*
* const account = Account.fromHeadlessWebAuthn('0x...')
* ```
*
* @param privateKey P256 private key.
* @returns Account.
*/
export function fromHeadlessWebAuthn<
const options extends fromHeadlessWebAuthn.Options,
>(
privateKey: Hex.Hex,
options: options | fromHeadlessWebAuthn.Options,
): fromHeadlessWebAuthn.ReturnValue<options> {
const { access, rpId, origin, internal_version } = options
const publicKey = P256.getPublicKey({ privateKey })
return from({
access,
internal_version,
keyType: 'webAuthn',
publicKey,
async sign({ hash }) {
const { metadata, payload } = WebAuthnP256.getSignPayload({
...options,
challenge: hash,
rpId,
origin,
})
const signature = P256.sign({
payload,
privateKey,
hash: true,
})
return SignatureEnvelope.serialize({
metadata,
signature,
publicKey,
type: 'webAuthn',
})
},
}) as never
}
export declare namespace fromHeadlessWebAuthn {
export type Options = Omit<
WebAuthnP256.getSignPayload.Options,
'challenge' | 'rpId' | 'origin'
> &
Pick<from.Parameters, 'access' | 'internal_version'> & {
rpId: string
origin: string
}
export type ReturnValue<options extends Options = Options> =
from.ReturnValue<options>
}
/**
* Instantiates an Account from a P256 private key.
*
* @example
* ```ts
* import { Account } from 'viem/tempo'
*
* const account = Account.fromP256('0x...')
* ```
*
* @param privateKey P256 private key.
* @returns Account.
*/
export function fromP256<const options extends fromP256.Options>(
privateKey: Hex.Hex,
options: options | fromP256.Options = {},
): fromP256.ReturnValue<options> {
const { access, internal_version } = options
const publicKey = P256.getPublicKey({ privateKey })
return from({
access,
internal_version,
keyType: 'p256',
publicKey,
async sign({ hash }) {
const signature = P256.sign({ payload: hash, privateKey })
return SignatureEnvelope.serialize({
signature,
publicKey,
type: 'p256',
})
},
}) as never
}
export declare namespace fromP256 {
export type Options = Pick<from.Parameters, 'access' | 'internal_version'>
export type ReturnValue<options extends Options = Options> =
from.ReturnValue<options>
}
/**
* Instantiates an Account from a Secp256k1 private key.
*
* @example
* ```ts
* import { Account } from 'viem/tempo'
*
* const account = Account.fromSecp256k1('0x...')
* ```
*
* @param privateKey Secp256k1 private key.
* @returns Account.
*/
export function fromSecp256k1<const options extends fromSecp256k1.Options>(
privateKey: Hex.Hex,
options: options | fromSecp256k1.Options = {},
): fromSecp256k1.ReturnValue<options> {
const { access, internal_version } = options
const publicKey = Secp256k1.getPublicKey({ privateKey })
return from({
access,
internal_version,
keyType: 'secp256k1',
publicKey,
async sign(parameters) {
const { hash } = parameters
const signature = Secp256k1.sign({ payload: hash, privateKey })
return Signature.toHex(signature)
},
}) as never
}
export declare namespace fromSecp256k1 {
export type Options = Pick<from.Parameters, 'access' | 'internal_version'>
export type ReturnValue<options extends Options = Options> =
from.ReturnValue<options>
}
/**
* Instantiates an Account from a WebAuthn credential.
*
* @example
*
* ### Create Passkey + Instantiate Account
*
* Create a credential with `WebAuthnP256.createCredential` and then instantiate
* a Viem Account with `Account.fromWebAuthnP256`.
*
* It is highly recommended to store the credential's public key in an external store
* for future use (ie. for future calls to `WebAuthnP256.getCredential`).
*
* ```ts
* import { Account, WebAuthnP256 } from 'viem/tempo'
* import { publicKeyStore } from './store'
*
* // 1. Create credential
* const credential = await WebAuthnP256.createCredential({ name: 'Example' })
*
* // 2. Instantiate account
* const account = Account.fromWebAuthnP256(credential)
*
* // 3. Store public key
* await publicKeyStore.set(credential.id, credential.publicKey)
*
* ```
*
* @example
*
* ### Get Credential + Instantiate Account
*
* Gets a credential from `WebAuthnP256.getCredential` and then instantiates
* an account with `Account.fromWebAuthnP256`.
*
* The `getPublicKey` function is required to fetch the public key paired with the credential
* from an external store. The public key is required to derive the account's address.
*
* ```ts
* import { Account, WebAuthnP256 } from 'viem/tempo'
* import { publicKeyStore } from './store'
*
* // 1. Get credential
* const credential = await WebAuthnP256.getCredential({
* async getPublicKey(credential) {
* // 2. Get public key from external store.
* return await publicKeyStore.get(credential.id)
* }
* })
*
* // 3. Instantiate account
* const account = Account.fromWebAuthnP256(credential)
* ```
*
* @param credential WebAuthnP256 credential.
* @returns Account.
*/
export function fromWebAuthnP256(
credential: fromWebAuthnP256.Credential,
options: fromWebAuthnP256.Options = {},
): fromWebAuthnP256.ReturnValue {
const { id } = credential
const publicKey = PublicKey.fromHex(credential.publicKey)
return from({
keyType: 'webAuthn',
publicKey,
async sign({ hash }) {
const { metadata, signature } = await WebAuthnP256.sign({
...options,
challenge: hash,
credentialId: id,
})
return SignatureEnvelope.serialize({
publicKey,
metadata,
signature,
type: 'webAuthn',
})
},
})
}
export declare namespace fromWebAuthnP256 {
export type Credential = {
id: WebAuthnP256.P256Credential['id']
publicKey: Hex.Hex
}
export type Options = {
getFn?: WebAuthnP256.sign.Options['getFn'] | undefined
rpId?: WebAuthnP256.sign.Options['rpId'] | undefined
}
export type ReturnValue = from.ReturnValue
}
/**
* Instantiates an Account from a P256 private key.
*
* @example
* ```ts
* import { Account } from 'viem/tempo'
* import { WebCryptoP256 } from 'ox'
*
* const keyPair = await WebCryptoP256.createKeyPair()
*
* const account = Account.fromWebCryptoP256(keyPair)
* ```
*
* @param keyPair WebCryptoP256 key pair.
* @returns Account.
*/
export function fromWebCryptoP256<
const options extends fromWebCryptoP256.Options,
>(
keyPair: Awaited<ReturnType<typeof WebCryptoP256.createKeyPair>>,
options: options | fromWebCryptoP256.Options = {},
): fromWebCryptoP256.ReturnValue<options> {
const { access, internal_version } = options
const { publicKey, privateKey } = keyPair
return from({
access,
internal_version,
keyType: 'p256',
publicKey,
async sign({ hash }) {
const signature = await WebCryptoP256.sign({ payload: hash, privateKey })
return SignatureEnvelope.serialize({
signature,
prehash: true,
publicKey,
type: 'p256',
})
},
}) as never
}
export declare namespace fromWebCryptoP256 {
export type Options = Pick<from.Parameters, 'access' | 'internal_version'>
export type ReturnValue<options extends Options = Options> =
from.ReturnValue<options>
}
export async function signKeyAuthorization(
account: LocalAccount,
parameters: signKeyAuthorization.Parameters,
): Promise<signKeyAuthorization.ReturnValue> {
const { chainId, key, expiry, limits, scopes } = parameters
const { accessKeyAddress, keyType: type } = resolveAccessKey(key)
const signature = await account.sign!({
hash: KeyAuthorization.getSignPayload({
address: accessKeyAddress,
chainId,
expiry,
limits,
scopes,
type,
}),
})
return KeyAuthorization.from({
address: accessKeyAddress,
chainId,
expiry,
limits,
scopes,
signature: SignatureEnvelope.from(signature),
type,
})
}
export declare namespace signKeyAuthorization {
type Parameters = Pick<
KeyAuthorization.KeyAuthorization,
'chainId' | 'expiry' | 'limits' | 'scopes'
> & {
key: resolveAccessKey.Parameters
}
type ReturnValue = KeyAuthorization.Signed
}
/** @internal */
// biome-ignore lint/correctness/noUnusedVariables: _
function fromBase(parameters: fromBase.Parameters): Account_base {
const {
keyType = 'secp256k1',
parentAddress,
source = 'privateKey',
internal_version = 'v2',
} = parameters
const address = parentAddress ?? Address.fromPublicKey(parameters.publicKey)
const publicKey = PublicKey.toHex(parameters.publicKey, {
includePrefix: false,
})
async function sign({ hash }: { hash: Hex.Hex }) {
const innerHash =
parentAddress && internal_version === 'v2'
? keccak256(Hex.concat('0x04', hash, parentAddress))
: hash
const signature = await parameters.sign({ hash: innerHash })
if (parentAddress)
return SignatureEnvelope.serialize(
SignatureEnvelope.from({
userAddress: parentAddress,
inner: SignatureEnvelope.from(signature),
type: 'keychain',
version: internal_version,
}),
)
return signature
}
return {
address: Address.checksum(address),
keyType,
sign,
async signAuthorization(parameters) {
const { chainId, nonce } = parameters
const address = parameters.contractAddress ?? parameters.address
const signature = await sign({
hash: hashAuthorization({ address, chainId, nonce }),
})
const envelope = SignatureEnvelope.from(signature)
if (envelope.type !== 'secp256k1')
throw new Error(
'Unsupported signature type. Expected `secp256k1` but got `' +
envelope.type +
'`.',
)
const { r, s, yParity } = envelope.signature
return {
address,
chainId,
nonce,
r: Hex.fromNumber(r, { size: 32 }),
s: Hex.fromNumber(s, { size: 32 }),
yParity,
}
},
async signMessage(parameters) {
const { message } = parameters
return await sign({ hash: hashMessage(message) })
},
async signTransaction(transaction, options) {
const { serializer = Transaction.serialize } = options ?? {}
const presign = (() => {
if ('feePayerSignature' in transaction && transaction.feePayerSignature)
return { ...transaction, feePayerSignature: null }
return transaction
})()
const signature = await sign({
hash: keccak256(await serializer(presign)),
})
const envelope = SignatureEnvelope.from(signature)
return await serializer(transaction, envelope as never)
},
async signTypedData(typedData) {
return await sign({ hash: hashTypedData(typedData) })
},
publicKey,
source,
type: 'local',
}
}
declare namespace fromBase {
export type Parameters = {
/** Parent address. */
parentAddress?: Address.Address | undefined
/** Public key. */
publicKey: PublicKey.PublicKey
/** Key type. */
keyType?: SignatureEnvelope.Type | undefined
/** Sign function. */
sign: NonNullable<LocalAccount['sign']>
/** Source. */
source?: string | undefined
/** Access key version. Will be removed in a future release. @deprecated @internal */
internal_version?: 'v1' | 'v2' | undefined
}
export type ReturnValue = Account_base
}
/** @internal */
// biome-ignore lint/correctness/noUnusedVariables: _
function fromRoot(parameters: fromRoot.Parameters): RootAccount {
const account = fromBase(parameters)
return {
...account,
source: 'root',
async signKeyAuthorization(key, parameters) {
const { chainId, expiry, limits, scopes } = parameters
const { accessKeyAddress, keyType: type } = resolveAccessKey(key)
const signature = await account.sign({
hash: KeyAuthorization.getSignPayload({
address: accessKeyAddress,
chainId,
expiry,
limits,
scopes,
type,
}),
})
const keyAuthorization = KeyAuthorization.from({
address: accessKeyAddress,
chainId,
expiry,
limits,
scopes,
signature: SignatureEnvelope.from(signature),
type,
})
return keyAuthorization
},
}
}
declare namespace fromRoot {
export type Parameters = fromBase.Parameters
export type ReturnValue = RootAccount
}
// biome-ignore lint/correctness/noUnusedVariables: _
function fromAccessKey(parameters: fromAccessKey.Parameters): AccessKeyAccount {
const { access } = parameters
const { address: parentAddress } = parseAccount(access)
const account = fromBase({ ...parameters, parentAddress })
return {
...account,
accessKeyAddress: Address.fromPublicKey(parameters.publicKey),
source: 'accessKey',
}
}
declare namespace fromAccessKey {
export type Parameters = fromBase.Parameters & {
/**
* Parent account to access.
* If defined, this account will act as an "access key", and use
* the parent account's address as the keychain address.
*/
access: viem_Account | Address.Address
}
export type ReturnValue = AccessKeyAccount
}
/** @internal */
export function resolveAccessKey(
accessKey: resolveAccessKey.Parameters,
): resolveAccessKey.ReturnType {
if ('accessKeyAddress' in accessKey)
return {
accessKeyAddress: accessKey.accessKeyAddress,
keyType: accessKey.keyType,
}
if ('publicKey' in accessKey && accessKey.publicKey)
return {
accessKeyAddress: Address.fromPublicKey(
PublicKey.fromHex(accessKey.publicKey),
),
keyType: accessKey.type,
}
return {
accessKeyAddress: accessKey.address,
keyType: accessKey.type,
}
}
export declare namespace resolveAccessKey {
type Parameters =
| Pick<AccessKeyAccount, 'accessKeyAddress' | 'keyType'>
| OneOf<
| {
/** Access key address. */
address: Address.Address
/** Key type. */
type: SignatureEnvelope.Type
}
| {
/** Access key public key. */
publicKey: Hex.Hex
/** Key type. */
type: SignatureEnvelope.Type
}
>
type ReturnType = {
accessKeyAddress: Address.Address
keyType: SignatureEnvelope.Type
}
}
// Export types required for inference.
// biome-ignore lint/performance/noBarrelFile: _
export {
/** @deprecated */
KeyAuthorization as z_KeyAuthorization,
/** @deprecated */
SignatureEnvelope as z_SignatureEnvelope,
/** @deprecated */
TxEnvelopeTempo as z_TxEnvelopeTempo,
} from 'ox/tempo'

13
node_modules/viem/tempo/Addresses.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
export const accountImplementation =
'0x7702c00000000000000000000000000000000000'
export const accountKeychain = '0xaAAAaaAA00000000000000000000000000000000'
export const accountRegistrar = '0x7702ac0000000000000000000000000000000000'
export const addressRegistry = '0xfdc0000000000000000000000000000000000000'
export const feeManager = '0xfeec000000000000000000000000000000000000'
export const nonceManager = '0x4e4F4E4345000000000000000000000000000000'
export const pathUsd = '0x20c0000000000000000000000000000000000000'
export const stablecoinDex = '0xdec0000000000000000000000000000000000000'
export const tip20Factory = '0x20fc000000000000000000000000000000000000'
export const tip403Registry = '0x403c000000000000000000000000000000000000'
export const validator = '0xcccccccc00000000000000000000000000000000'
export const zoneOutbox = '0x1c00000000000000000000000000000000000002'

81
node_modules/viem/tempo/Capabilities.ts generated vendored Normal file
View File

@@ -0,0 +1,81 @@
import type { Address } from 'abitype'
import type { DefaultCapabilitiesSchema } from '../types/capabilities.js'
import type { Hex } from '../types/misc.js'
import type { ExactPartial, OneOf } from '../types/utils.js'
import type { DecodeErrorResultReturnType } from '../utils/index.js'
import type { TransactionRequestTempo } from './Transaction.js'
export type Schema = Omit<DefaultCapabilitiesSchema, 'sendCalls'> & {
fillTransaction: {
ReturnType: FillTransactionCapabilities
}
sendCalls: {
Request: ExactPartial<TransactionRequestTempo>
}
}
export type FillTransactionCapabilities = {
autoSwap?:
| {
calls: readonly { to: Address; data: Hex; value: Hex }[]
maxIn: SwapAmount
minOut: SwapAmount
slippage: number
}
| undefined
balanceDiffs?: Readonly<Record<Address, readonly BalanceDiff[]>> | undefined
error?:
| OneOf<
| (DecodeErrorResultReturnType & {
data: Hex
message: string
})
| { errorName: 'unknown'; message: string }
>
| undefined
fee?:
| {
amount: Hex
decimals: number
formatted: string
symbol: string
}
| undefined
requireFunds?:
| {
amount: Hex
decimals: number
formatted: string
token: Address
symbol: string
}
| undefined
sponsor?:
| {
address: Address
name?: string | undefined
url?: string | undefined
}
| undefined
sponsored?: boolean | undefined
}
export type BalanceDiff = {
address: Address
decimals: number
direction: 'incoming' | 'outgoing'
formatted: string
name: string
recipients: readonly Address[]
symbol: string
value: Hex
}
export type SwapAmount = {
decimals: number
formatted: string
name: string
symbol: string
token: Address
value: Hex
}

4516
node_modules/viem/tempo/Decorator.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

34
node_modules/viem/tempo/Expiry.ts generated vendored Normal file
View File

@@ -0,0 +1,34 @@
/** Returns a unix timestamp `n` days from now. */
export function days(n: number) {
return Math.floor(Date.now() / 1000) + n * 24 * 60 * 60
}
/** Returns a unix timestamp `n` hours from now. */
export function hours(n: number) {
return Math.floor(Date.now() / 1000) + n * 60 * 60
}
/** Returns a unix timestamp `n` minutes from now. */
export function minutes(n: number) {
return Math.floor(Date.now() / 1000) + n * 60
}
/** Returns a unix timestamp `n` months (30 days) from now. */
export function months(n: number) {
return Math.floor(Date.now() / 1000) + n * 30 * 24 * 60 * 60
}
/** Returns a unix timestamp `n` seconds from now. */
export function seconds(n: number) {
return Math.floor(Date.now() / 1000) + n
}
/** Returns a unix timestamp `n` weeks from now. */
export function weeks(n: number) {
return Math.floor(Date.now() / 1000) + n * 7 * 24 * 60 * 60
}
/** Returns a unix timestamp `n` years (365 days) from now. */
export function years(n: number) {
return Math.floor(Date.now() / 1000) + n * 365 * 24 * 60 * 60
}

149
node_modules/viem/tempo/Formatters.ts generated vendored Normal file
View File

@@ -0,0 +1,149 @@
// TODO: Find opportunities to make this file less duplicated + more simplified with Viem v3.
import type { Address } from 'abitype'
import * as Hex from 'ox/Hex'
import {
Transaction as ox_Transaction,
TransactionRequest as ox_TransactionRequest,
} from 'ox/tempo'
import type { Account as viem_Account } from '../accounts/types.js'
import { parseAccount } from '../accounts/utils/parseAccount.js'
import { formatTransaction as viem_formatTransaction } from '../utils/formatters/transaction.js'
import { formatTransactionReceipt as viem_formatTransactionReceipt } from '../utils/formatters/transactionReceipt.js'
import { formatTransactionRequest as viem_formatTransactionRequest } from '../utils/formatters/transactionRequest.js'
import type { Account } from './Account.js'
import {
isTempo,
type Transaction,
type TransactionReceipt,
type TransactionReceiptRpc,
type TransactionRequest,
type TransactionRequestRpc,
type TransactionRpc,
} from './Transaction.js'
export function formatTransaction(
transaction: TransactionRpc,
): Transaction<bigint, number, boolean> {
if (!isTempo(transaction)) return viem_formatTransaction(transaction as never)
const {
feePayerSignature,
gasPrice: _,
nonce,
...tx
} = ox_Transaction.fromRpc(transaction as never) as ox_Transaction.Tempo
return {
...tx,
accessList: tx.accessList!,
feePayerSignature: feePayerSignature
? {
r: Hex.fromNumber(feePayerSignature.r, { size: 32 }),
s: Hex.fromNumber(feePayerSignature.s, { size: 32 }),
v: BigInt(feePayerSignature.v ?? 27),
yParity: feePayerSignature.yParity,
}
: undefined,
nonce: Number(nonce),
typeHex:
ox_Transaction.toRpcType[
tx.type as keyof typeof ox_Transaction.toRpcType
],
type: tx.type as 'tempo',
}
}
export function formatTransactionReceipt(
receipt: TransactionReceiptRpc,
): TransactionReceipt {
return viem_formatTransactionReceipt(receipt as never)
}
export function formatTransactionRequest(
r: TransactionRequest,
action?: string | undefined,
): TransactionRequestRpc {
const request = r as TransactionRequest & {
account?: viem_Account | Address | undefined
}
const account = request.account
? parseAccount<Account | viem_Account | Address>(request.account)
: undefined
// If the request is not a Tempo transaction, route to Viem formatter.
if (!isTempo(request))
return viem_formatTransactionRequest(
r as never,
action,
) as TransactionRequestRpc
if (action)
request.calls = request.calls ?? [
{
to:
r.to ||
(!r.data || r.data === '0x'
? '0x0000000000000000000000000000000000000000'
: undefined),
value: r.value,
data: r.data,
},
]
// If we have marked the transaction as intended to be paid
// by a fee payer (feePayer: true), we will not use the fee token
// as the fee payer will choose their fee token.
if (request.feePayer === true) delete request.feeToken
const rpc = ox_TransactionRequest.toRpc({
...request,
type: 'tempo',
} as never)
if (action === 'estimateGas') {
rpc.maxFeePerGas = undefined
rpc.maxPriorityFeePerGas = undefined
}
rpc.to = undefined
rpc.data = undefined
rpc.value = undefined
const [keyType, keyData] = (() => {
const type =
account && 'keyType' in account ? account.keyType : account?.source
if (!type) return [undefined, undefined]
if (type === 'webAuthn')
// TODO: derive correct bytes size of key data based on webauthn create metadata.
return ['webAuthn', `0x${'ff'.repeat(1400)}`]
if (['p256', 'secp256k1'].includes(type)) return [type, undefined]
return [undefined, undefined]
})()
const keyId =
account && 'accessKeyAddress' in account
? account.accessKeyAddress
: undefined
if (account) rpc.from = account.address
return {
...rpc,
...(keyData ? { keyData } : {}),
...(keyId ? { keyId } : {}),
...(keyType ? { keyType } : {}),
...(typeof request.feePayer !== 'undefined'
? {
feePayer:
typeof request.feePayer === 'object'
? parseAccount(request.feePayer)
: request.feePayer,
}
: {}),
...('feePayerSignature' in request &&
request.feePayerSignature !== undefined
? { feePayerSignature: request.feePayerSignature }
: {}),
} as never
}

17
node_modules/viem/tempo/Hardfork.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
export const hardforks = [
'genesis',
't0',
't1',
't1a',
't1b',
't1c',
't2',
't3',
] as const
export type Hardfork = (typeof hardforks)[number]
/** Returns `true` if `current` is before `target`. */
export function lt(current: string, target: Hardfork): boolean {
return hardforks.indexOf(current as Hardfork) < hardforks.indexOf(target)
}

2
node_modules/viem/tempo/P256.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
// biome-ignore lint/performance/noBarrelFile: _
export { randomPrivateKey } from 'ox/P256'

118
node_modules/viem/tempo/Storage.ts generated vendored Normal file
View File

@@ -0,0 +1,118 @@
import type { MaybePromise } from '../types/utils.js'
export type Storage = {
getItem(key: string): MaybePromise<string | null | undefined>
setItem(key: string, value: string): MaybePromise<void>
removeItem(key: string): MaybePromise<void>
}
/**
* Wraps a base storage with an optional key prefix and request
* deduplication — concurrent `getItem` calls for the same key share
* a single in-flight promise.
*
* @example
* ```ts
* import * as Storage from 'viem/tempo/zones'
*
* const storage = Storage.from(Storage.memory(), { key: 'tempo' })
* await storage.setItem('foo', 'bar')
* // stored under "tempo:foo"
* ```
*/
export function from(storage: Storage, options: from.Options = {}): Storage {
const { key } = options
const prefix = key ? `${key}:` : ''
const inflight = new Map<string, Promise<string | null | undefined>>()
return {
getItem(k) {
const fullKey = `${prefix}${k}`
const existing = inflight.get(fullKey)
if (existing) return existing
const result = Promise.resolve(storage.getItem(fullKey)).finally(() => {
inflight.delete(fullKey)
})
inflight.set(fullKey, result)
return result
},
setItem(k, value) {
const fullKey = `${prefix}${k}`
inflight.delete(fullKey)
return storage.setItem(fullKey, value)
},
removeItem(k) {
const fullKey = `${prefix}${k}`
inflight.delete(fullKey)
return storage.removeItem(fullKey)
},
}
}
export declare namespace from {
type Options = {
/** Key prefix prepended to all storage keys. */
key?: string | undefined
}
}
/** Creates an in-memory storage backed by a `Map`. */
export function memory(options: from.Options = {}): Storage {
const store = new Map<string, string>()
return from(
{
getItem(key) {
return store.get(key) ?? null
},
setItem(key, value) {
store.set(key, value)
},
removeItem(key) {
store.delete(key)
},
},
options,
)
}
/** Creates a storage backed by `globalThis.sessionStorage`. */
export function session(options: from.Options = {}): Storage {
return from(
{
getItem(key) {
return globalThis.sessionStorage.getItem(key)
},
setItem(key, value) {
try {
globalThis.sessionStorage.setItem(key, value)
} catch {}
},
removeItem(key) {
globalThis.sessionStorage.removeItem(key)
},
},
options,
)
}
let _default: Storage | undefined
/**
* Returns the default storage for the current environment.
*
* Returns a singleton so that the zone transport and actions share the
* same instance without requiring explicit plumbing.
*
* - Browser: `sessionStorage`
* - Server/unsupported: in-memory `Map`-based storage
*/
export function defaultStorage(): Storage {
if (_default) return _default
if (
typeof globalThis !== 'undefined' &&
'sessionStorage' in globalThis &&
globalThis.sessionStorage
)
_default = session()
else _default = memory()
return _default
}

1
node_modules/viem/tempo/TokenIds.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export const pathUsd = 0n

391
node_modules/viem/tempo/Transaction.ts generated vendored Normal file
View File

@@ -0,0 +1,391 @@
// TODO: Find opportunities to make this file less duplicated + more simplified with Viem v3.
import type { Address } from 'abitype'
import * as Hex from 'ox/Hex'
import * as Secp256k1 from 'ox/Secp256k1'
import * as Signature from 'ox/Signature'
import {
type AuthorizationTempo,
type KeyAuthorization,
type TransactionReceipt as ox_TransactionReceipt,
SignatureEnvelope,
type TempoAddress,
TxEnvelopeTempo as TxTempo,
} from 'ox/tempo'
import type { Account } from '../accounts/types.js'
import type { FeeValuesEIP1559 } from '../types/fee.js'
import type { Signature as viem_Signature } from '../types/misc.js'
import type {
RpcTransaction as viem_RpcTransaction,
RpcTransactionRequest as viem_RpcTransactionRequest,
} from '../types/rpc.js'
import type {
AccessList,
TransactionBase,
TransactionRequestBase,
TransactionSerializableBase,
TransactionSerializedGeneric,
Transaction as viem_Transaction,
TransactionReceipt as viem_TransactionReceipt,
TransactionRequest as viem_TransactionRequest,
TransactionSerializable as viem_TransactionSerializable,
TransactionSerialized as viem_TransactionSerialized,
TransactionType as viem_TransactionType,
} from '../types/transaction.js'
import type { ExactPartial, OneOf, PartialBy } from '../types/utils.js'
import { getTransactionType as viem_getTransactionType } from '../utils/transaction/getTransactionType.js'
import {
type ParseTransactionReturnType,
parseTransaction as viem_parseTransaction,
} from '../utils/transaction/parseTransaction.js'
import { serializeTransaction as viem_serializeTransaction } from '../utils/transaction/serializeTransaction.js'
export type Transaction<
bigintType = bigint,
numberType = number,
pending extends boolean = false,
> = OneOf<
| viem_Transaction<bigintType, numberType, pending>
| TransactionTempo<bigintType, numberType, pending>
>
export type TransactionRpc<pending extends boolean = false> = OneOf<
| viem_RpcTransaction<pending>
| (Omit<
TransactionTempo<Hex.Hex, Hex.Hex, pending, '0x76'>,
'authorizationList' | 'keyAuthorization' | 'signature'
> & {
authorizationList?: AuthorizationTempo.ListRpc | undefined
keyAuthorization?: KeyAuthorization.Rpc | null | undefined
signature: SignatureEnvelope.SignatureEnvelopeRpc
})
>
export type TransactionTempo<
quantity = bigint,
index = number,
isPending extends boolean = boolean,
type = 'tempo',
> = PartialBy<
Omit<TransactionBase<quantity, index, isPending>, 'input' | 'value' | 'to'>,
'r' | 's' | 'v' | 'yParity'
> & {
accessList: AccessList
authorizationList?: AuthorizationTempo.ListSigned<quantity, index> | undefined
calls: readonly TxTempo.Call<quantity>[]
chainId: index
feeToken?: Address | undefined
feePayerSignature?: viem_Signature | undefined
keyAuthorization?: KeyAuthorization.Signed<quantity, index> | null | undefined
nonceKey?: quantity | undefined
signature: SignatureEnvelope.SignatureEnvelope
type: type
validBefore?: index | undefined
validAfter?: index | undefined
} & FeeValuesEIP1559<quantity>
export type TransactionRequest<
bigintType = bigint,
numberType = number,
> = OneOf<
| viem_TransactionRequest<bigintType, numberType>
| TransactionRequestTempo<bigintType, numberType>
>
export type TransactionRequestRpc = OneOf<
viem_RpcTransactionRequest | TransactionRequestTempo<Hex.Hex, Hex.Hex, '0x76'>
>
export type TransactionReceipt<
quantity = bigint,
index = number,
status = 'success' | 'reverted',
type = TransactionType,
> = viem_TransactionReceipt<quantity, index, status, type> & {
feePayer?: Address | undefined
feeToken?: Address | undefined
}
export type TransactionReceiptRpc = TransactionReceipt<
Hex.Hex,
Hex.Hex,
ox_TransactionReceipt.RpcStatus,
ox_TransactionReceipt.RpcType
>
export type TransactionRequestTempo<
quantity = bigint,
index = number,
type = 'tempo',
> = TransactionRequestBase<quantity, index, type> &
ExactPartial<FeeValuesEIP1559<quantity>> & {
accessList?: AccessList | undefined
keyAuthorization?: KeyAuthorization.Signed<quantity, index> | undefined
calls?: readonly TxTempo.Call<quantity, TempoAddress.Address>[] | undefined
feePayer?: Account | true | undefined
feeToken?: TempoAddress.Address | bigint | undefined
nonceKey?: 'expiring' | quantity | undefined
validBefore?: index | undefined
validAfter?: index | undefined
}
export type TransactionSerializable = OneOf<
viem_TransactionSerializable | TransactionSerializableTempo
>
export type TransactionSerializableTempo<
quantity = bigint,
index = number,
> = TransactionSerializableBase<quantity, index> &
ExactPartial<FeeValuesEIP1559<quantity>> & {
accessList?: AccessList | undefined
calls: readonly TxTempo.Call<quantity>[]
chainId: number
feeToken?: Address | bigint | undefined
feePayerSignature?: viem_Signature | null | undefined
from?: Address | undefined
keyAuthorization?: KeyAuthorization.Signed<quantity, index> | undefined
nonceKey?: quantity | undefined
signature?: SignatureEnvelope.SignatureEnvelope<quantity, index> | undefined
validBefore?: index | undefined
validAfter?: index | undefined
type?: 'tempo' | undefined
}
export type TransactionSerialized<
type extends TransactionType = TransactionType,
> = viem_TransactionSerialized<type> | TransactionSerializedTempo
export type TransactionSerializedTempo = `0x76${string}`
export type TransactionSerializedFeePayer = `0x78${string}`
export type TransactionType = viem_TransactionType | 'tempo'
export function getType(
transaction: Record<string, unknown>,
): Transaction['type'] {
const account = transaction.account as
| { keyType?: string | undefined; source?: string | undefined }
| undefined
if (
(account?.keyType && account.keyType !== 'secp256k1') ||
account?.source === 'accessKey' ||
typeof transaction.calls !== 'undefined' ||
typeof transaction.feePayer !== 'undefined' ||
typeof transaction.feeToken !== 'undefined' ||
typeof transaction.keyAuthorization !== 'undefined' ||
typeof transaction.nonceKey !== 'undefined' ||
typeof transaction.signature !== 'undefined' ||
typeof transaction.validBefore !== 'undefined' ||
typeof transaction.validAfter !== 'undefined'
)
return 'tempo' as never
if (transaction.type) return transaction.type as never
return viem_getTransactionType(transaction) as never
}
export function isTempo(transaction: Record<string, unknown>) {
try {
const type = getType(transaction)
return type === 'tempo'
} catch {
return false
}
}
export function deserialize<
const serialized extends TransactionSerializedGeneric,
>(serializedTransaction: serialized): deserialize.ReturnValue<serialized> {
const type = Hex.slice(serializedTransaction, 0, 1)
if (type === '0x76' || type === '0x78')
return deserializeTempo(serializedTransaction as `0x76${string}`) as never
return viem_parseTransaction(serializedTransaction) as never
}
export declare namespace deserialize {
export type ReturnValue<
serialized extends
TransactionSerializedGeneric = TransactionSerializedGeneric,
> = serialized extends TransactionSerializedTempo
? TransactionSerializableTempo
: serialized extends TransactionSerializedFeePayer
? TransactionSerializableTempo
: ParseTransactionReturnType<serialized>
}
export async function serialize(
transaction: TransactionSerializable & {
feePayer?: Account | true | undefined
from?: TempoAddress.Address | undefined
},
signature?:
| OneOf<SignatureEnvelope.SignatureEnvelope | viem_Signature>
| undefined,
) {
// If the transaction is not a Tempo transaction, route to Viem serializer.
if (!isTempo(transaction)) {
if (signature && 'type' in signature && signature.type !== 'secp256k1')
throw new Error(
'Unsupported signature type. Expected `secp256k1` but got `' +
signature.type +
'`.',
)
if (signature && 'type' in signature) {
const { r, s, yParity } = signature?.signature!
return viem_serializeTransaction(transaction as never, {
r: Hex.fromNumber(r, { size: 32 }),
s: Hex.fromNumber(s, { size: 32 }),
yParity,
})
}
return viem_serializeTransaction(transaction as never, signature)
}
const type = getType(transaction)
if (type === 'tempo') return serializeTempo(transaction as never, signature)
throw new Error('Unsupported transaction type')
}
////////////////////////////////////////////////////////////////////////////////////
// Internal
/** @internal */
function deserializeTempo(
serializedTransaction: TransactionSerializedTempo,
): TransactionSerializableTempo {
const { feePayerSignature, nonce, ...tx } = TxTempo.deserialize(
serializedTransaction,
)
return {
...tx,
nonce: Number(nonce ?? 0n),
feePayerSignature: feePayerSignature
? {
r: Hex.fromNumber(feePayerSignature.r, { size: 32 }),
s: Hex.fromNumber(feePayerSignature.s, { size: 32 }),
yParity: feePayerSignature.yParity,
}
: feePayerSignature,
} satisfies TransactionSerializableTempo
}
/** @internal */
async function serializeTempo(
transaction: TransactionSerializableTempo & {
feePayer?: Account | true | undefined
from?: Address | undefined
},
sig?: OneOf<SignatureEnvelope.SignatureEnvelope | viem_Signature> | undefined,
) {
const signature = (() => {
if (transaction.signature) return transaction.signature
if (sig && 'type' in sig) return sig as SignatureEnvelope.SignatureEnvelope
if (sig)
return SignatureEnvelope.from({
r: BigInt(sig.r!),
s: BigInt(sig.s!),
yParity: Number(sig.yParity!),
})
return undefined
})()
const { chainId, feePayer, nonce, ...rest } = transaction
const feePayerSignature = (() => {
const feePayerSignature = transaction.feePayerSignature
if (feePayerSignature)
return {
r: BigInt(feePayerSignature.r!),
s: BigInt(feePayerSignature.s!),
yParity: Number(feePayerSignature.yParity),
}
if (feePayerSignature === null || feePayer) return null
return undefined
})()
const transaction_ox = {
...rest,
calls: rest.calls?.length
? rest.calls
: [
{
to:
rest.to ||
(!rest.data || rest.data === '0x'
? '0x0000000000000000000000000000000000000000'
: undefined),
value: rest.value,
data: rest.data,
},
],
chainId: Number(chainId),
feePayerSignature,
type: 'tempo',
...(nonce ? { nonce: BigInt(nonce) } : {}),
} satisfies TxTempo.TxEnvelopeTempo
// If we have marked the transaction as intended to be paid
// by a fee payer (feePayer: true), we will not use the fee token
// as the fee payer will choose their fee token.
if (feePayer === true) delete transaction_ox.feeToken
if (signature && typeof transaction.feePayer === 'object') {
const tx = TxTempo.from(transaction_ox, {
signature,
})
const sender = (() => {
if (transaction.from) return transaction.from
if (signature.type === 'secp256k1')
return Secp256k1.recoverAddress({
payload: TxTempo.getSignPayload(tx),
signature: signature.signature,
})
throw new Error('Unable to extract sender from transaction or signature.')
})()
const hash = TxTempo.getFeePayerSignPayload(tx, {
sender,
})
const feePayerSignature = await transaction.feePayer.sign!({
hash,
})
return TxTempo.serialize(tx, {
feePayerSignature: Signature.from(feePayerSignature),
})
}
if (feePayer === true) {
if (signature)
return TxTempo.serialize(transaction_ox, {
format: 'feePayer',
sender: transaction.from,
signature,
})
return TxTempo.serialize(transaction_ox, {
feePayerSignature: null,
})
}
return TxTempo.serialize(
// If we have specified a fee payer, the user will not be signing over the fee token.
// Defer the fee token signing to the fee payer.
{ ...transaction_ox, ...(feePayer ? { feeToken: undefined } : {}) },
{
feePayerSignature: undefined,
signature,
},
)
}
// Export types required for inference.
// biome-ignore lint/performance/noBarrelFile: _
export {
/** @deprecated */
KeyAuthorization as z_KeyAuthorization,
/** @deprecated */
SignatureEnvelope as z_SignatureEnvelope,
/** @deprecated */
TxEnvelopeTempo as z_TxEnvelopeTempo,
} from 'ox/tempo'

301
node_modules/viem/tempo/Transport.ts generated vendored Normal file
View File

@@ -0,0 +1,301 @@
import * as Address from 'ox/Address'
import * as Hash from 'ox/Hash'
import * as Hex from 'ox/Hex'
import * as Provider from 'ox/Provider'
import * as RpcRequest from 'ox/RpcRequest'
import type { LocalAccount } from '../accounts/types.js'
import { getTransactionReceipt } from '../actions/public/getTransactionReceipt.js'
import { sendTransaction } from '../actions/wallet/sendTransaction.js'
import { sendTransactionSync } from '../actions/wallet/sendTransactionSync.js'
import { createClient } from '../clients/createClient.js'
import {
createTransport,
type Transport,
} from '../clients/transports/createTransport.js'
import type { Chain } from '../types/chain.js'
import type { ChainConfig } from './chainConfig.js'
import * as Transaction from './Transaction.js'
type RelayProxyParameters = {
/** Policy for how the relay should handle sponsored transactions. Defaults to `'sign-only'`. */
policy?: 'sign-only' | 'sign-and-broadcast' | undefined
}
export type FeePayer = Transport<typeof withFeePayer.type>
export type Relay = Transport<typeof withRelay.type>
/**
* Creates a relay transport that routes requests between
* the default transport or the relay transport.
*
* All `eth_fillTransaction` requests are sent to the relay with the request's
* `feePayer` value preserved so the relay can decide whether to sponsor the transaction.
*
* The policy parameter controls how the relay handles sponsored transactions:
* - `'sign-only'`: Relay co-signs the transaction and returns it to the client transport, which then broadcasts it via the default transport
* - `'sign-and-broadcast'`: Relay co-signs and broadcasts the transaction directly
*
* @param defaultTransport - The default transport to use.
* @param relayTransport - The relay transport to use.
* @param parameters - Configuration parameters.
* @returns A relay transport.
*/
export function withRelay(
defaultTransport: Transport,
relayTransport: Transport,
parameters?: withRelay.Parameters,
): withRelay.ReturnValue {
const { policy = 'sign-only' } = parameters ?? {}
return (config) => {
const transport_default = defaultTransport(config)
const transport_relay = relayTransport(config)
return createTransport({
key: withRelay.type,
name: 'Relay Proxy',
async request({ method, params }, options) {
if (method === 'eth_fillTransaction')
return transport_relay.request({ method, params }, options) as never
if (
method === 'eth_sendRawTransactionSync' ||
method === 'eth_sendRawTransaction'
) {
const serialized = (params as any)[0] as `0x76${string}`
const transaction = Transaction.deserialize(serialized)
// Serialized Tempo envelopes encode `feePayer: true` as a missing fee payer
// signature until the relay co-signs the transaction.
if (transaction.feePayerSignature === null) {
// For 'sign-and-broadcast', relay signs and broadcasts
if (policy === 'sign-and-broadcast')
return transport_relay.request(
{ method, params },
options,
) as never
// For 'sign-only', request signature from relay using eth_signRawTransaction
{
// Request signature from relay using eth_signRawTransaction
const signedTransaction = await transport_relay.request(
{
method: 'eth_signRawTransaction',
params: [serialized],
},
options,
)
// Broadcast the signed transaction via the default transport
return transport_default.request(
{ method, params: [signedTransaction] },
options,
) as never
}
}
}
return (await transport_default.request(
{ method, params },
options,
)) as never
},
type: withRelay.type,
})
}
}
export declare namespace withRelay {
export const type = 'relay'
export type Parameters = RelayProxyParameters
export type ReturnValue = Relay
}
/** @deprecated Use `withRelay` instead. */
export function withFeePayer(
defaultTransport: Transport,
relayTransport: Transport,
parameters?: withFeePayer.Parameters,
): withFeePayer.ReturnValue {
const { policy = 'sign-only' } = parameters ?? {}
return (config) => {
const transport_default = defaultTransport(config)
const transport_relay = relayTransport(config)
return createTransport({
key: withFeePayer.type,
name: 'Relay Proxy',
async request({ method, params }, options) {
if (method === 'eth_fillTransaction') {
const request = (params as readonly unknown[] | undefined)?.[0]
if (
request &&
typeof request === 'object' &&
'feePayer' in request &&
request.feePayer === true
)
return transport_relay.request({ method, params }, options) as never
}
if (
method === 'eth_sendRawTransactionSync' ||
method === 'eth_sendRawTransaction'
) {
const serialized = (params as any)[0] as `0x76${string}`
const transaction = Transaction.deserialize(serialized)
// Serialized Tempo envelopes encode `feePayer: true` as a missing fee payer
// signature until the relay co-signs the transaction.
if (transaction.feePayerSignature === null) {
// For 'sign-and-broadcast', relay signs and broadcasts
if (policy === 'sign-and-broadcast')
return transport_relay.request(
{ method, params },
options,
) as never
// For 'sign-only', request signature from relay using eth_signRawTransaction
{
// Request signature from relay using eth_signRawTransaction
const signedTransaction = await transport_relay.request(
{
method: 'eth_signRawTransaction',
params: [serialized],
},
options,
)
// Broadcast the signed transaction via the default transport
return transport_default.request(
{ method, params: [signedTransaction] },
options,
) as never
}
}
}
return (await transport_default.request(
{ method, params },
options,
)) as never
},
type: withFeePayer.type,
})
}
}
export declare namespace withFeePayer {
export const type = 'feePayer'
export type Parameters = {
/** Policy for how the fee payer should handle transactions. Defaults to `'sign-only'`. */
policy?: 'sign-only' | 'sign-and-broadcast' | undefined
}
export type ReturnValue = FeePayer
}
/**
* Creates a transport that instruments a compatibility layer for
* `wallet_` RPC actions (`sendCalls`, `getCallsStatus`, etc).
*
* @param transport - Transport to wrap.
* @returns Transport.
*/
export function walletNamespaceCompat(
transport: Transport,
options: walletNamespaceCompat.Parameters,
): Transport {
const { account } = options
const sendCallsMagic = Hash.keccak256(Hex.fromString('TEMPO_5792'))
return (options) => {
const t = transport(options)
const chain = options.chain as Chain & ChainConfig
return {
...t,
async request(args: never) {
const request = RpcRequest.from(args)
const client = createClient({
chain,
transport,
})
if (request.method === 'wallet_sendCalls') {
const params = request.params[0] ?? {}
const { capabilities, chainId, from } = params
const { sync, ...properties } = capabilities ?? {}
if (!chainId) throw new Provider.UnsupportedChainIdError()
if (Number(chainId) !== client.chain.id)
throw new Provider.UnsupportedChainIdError()
if (from && !Address.isEqual(from, account.address))
throw new Provider.DisconnectedError()
const calls = (params.calls ?? []).map((call) => ({
to: call.to,
value: call.value ? BigInt(call.value) : undefined,
data: call.data,
}))
const hash = await (async () => {
if (!sync)
return sendTransaction(client, {
account,
...(properties ? properties : {}),
calls,
})
const { transactionHash } = await sendTransactionSync(client, {
account,
...(properties ? properties : {}),
calls,
})
return transactionHash
})()
const id = Hex.concat(hash, Hex.padLeft(chainId, 32), sendCallsMagic)
return {
capabilities: { sync },
id,
}
}
if (request.method === 'wallet_getCallsStatus') {
const [id] = request.params ?? []
if (!id) throw new Error('`id` not found')
if (!id.endsWith(sendCallsMagic.slice(2)))
throw new Error('`id` not supported')
Hex.assert(id)
const hash = Hex.slice(id, 0, 32)
const chainId = Hex.slice(id, 32, 64)
const receipt = await getTransactionReceipt(client, { hash })
return {
atomic: true,
chainId: Number(chainId),
id,
receipts: [receipt],
status: receipt.status === 'success' ? 200 : 500,
version: '2.0.0',
}
}
return t.request(args)
},
} as never
}
}
export declare namespace walletNamespaceCompat {
export type Parameters = {
account: LocalAccount
}
}

149
node_modules/viem/tempo/WebAuthnP256.ts generated vendored Normal file
View File

@@ -0,0 +1,149 @@
import * as Bytes from 'ox/Bytes'
import type * as Hex from 'ox/Hex'
import * as PublicKey from 'ox/PublicKey'
import * as WebAuthnP256 from 'ox/WebAuthnP256'
export type P256Credential = {
id: WebAuthnP256.P256Credential['id']
publicKey: Hex.Hex
raw: WebAuthnP256.P256Credential['raw']
}
/**
* Creates a WebAuthn credential (ie. a passkey).
*
* This function returns the credential object, which includes the public key.
* It is recommended to store the public key against the credential in an external store
* as it is not possible to extract a public key from a credential after it has been created.
*
* @example
* ```ts
* import { WebAuthnP256 } from 'viem/tempo'
*
* const credential = await WebAuthnP256.createCredential({ name: 'Example' })
* // {
* // id: 'oZ48...',
* // publicKey: '0x...',
* // }
* ```
*
* @param parameters WebAuthnP256 createCredential options.
* @returns WebAuthn credential.
*/
export async function createCredential(
parameters: createCredential.Parameters,
): Promise<createCredential.ReturnValue> {
const { createFn, label, rpId, userId } = parameters
const credential = await WebAuthnP256.createCredential({
...parameters,
authenticatorSelection: {
...parameters.authenticatorSelection,
requireResidentKey: true,
residentKey: 'required',
userVerification: 'required',
},
createFn,
extensions: {
...parameters.extensions,
credProps: true,
},
rp: rpId
? {
id: rpId,
name: rpId,
}
: undefined,
name: undefined as never,
user: {
displayName: label,
id: new Uint8Array(userId ?? Bytes.fromString(label)),
name: label,
},
})
return {
id: credential.id,
publicKey: PublicKey.toHex(credential.publicKey, {
includePrefix: false,
}),
raw: credential.raw,
}
}
export declare namespace createCredential {
export type Parameters = Omit<
WebAuthnP256.createCredential.Options,
'publicKey' | 'rp' | 'signal' | 'user'
> & {
/**
* Credential creation function. Useful for environments that do not support
* the WebAuthn API natively (i.e. React Native or testing environments).
*
* @default window.navigator.credentials.create
*/
createFn?: WebAuthnP256.createCredential.Options['createFn'] | undefined
/** Label. */
label: string
/** Relying Party ID. */
rpId?: string | undefined
/** User ID. */
userId?: Bytes.Bytes | undefined
}
export type ReturnValue = P256Credential
}
/**
* Gets a WebAuthn credential (ie. a passkey), and optionally signs over a digest/hash.
*
* A `getPublicKey` function is required to fetch the public key paired with the credential
* from an external store. It is not possible to extract a public key from a credential after
* the credential has been created with `WebAuthnP256.createCredential`.
*
* @example
* ```ts
* import { WebAuthnP256 } from 'viem/tempo'
*
* const credential = await WebAuthnP256.getCredential({
* async getPublicKey(credential) {
* // Get public key from store
* return store.getPublicKey(credential.id)
* }
* })
* ```
*
* @param parameters WebAuthnP256 getCredential options.
* @returns WebAuthn credential.
*/
export async function getCredential(
parameters: getCredential.Parameters,
): Promise<getCredential.ReturnValue> {
const { metadata, raw, signature } = await WebAuthnP256.sign({
...parameters,
challenge: parameters.hash ?? '0x',
})
const publicKey = await parameters.getPublicKey(raw)
return {
id: raw.id,
metadata,
publicKey,
raw,
signature,
}
}
export declare namespace getCredential {
export type Parameters = Omit<
WebAuthnP256.sign.Options,
'challenge' | 'mediation' | 'publicKey' | 'signal'
> & {
hash?: Hex.Hex | undefined
getPublicKey: (
credential: WebAuthnP256.P256Credential['raw'],
) => Promise<Hex.Hex>
}
export type ReturnValue = WebAuthnP256.sign.ReturnType & {
id: string
publicKey: Hex.Hex
}
}

2
node_modules/viem/tempo/WebCryptoP256.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
// biome-ignore lint/performance/noBarrelFile: _
export { createKeyPair } from 'ox/WebCryptoP256'

901
node_modules/viem/tempo/actions/accessKey.ts generated vendored Normal file
View File

@@ -0,0 +1,901 @@
import type { Address } from 'abitype'
import type { KeyAuthorization } from 'ox/tempo'
import type { Account } from '../../accounts/types.js'
import { parseAccount } from '../../accounts/utils/parseAccount.js'
import { readContract } from '../../actions/public/readContract.js'
import { sendTransaction } from '../../actions/wallet/sendTransaction.js'
import { sendTransactionSync } from '../../actions/wallet/sendTransactionSync.js'
import type { WriteContractReturnType } from '../../actions/wallet/writeContract.js'
import { writeContract } from '../../actions/wallet/writeContract.js'
import { writeContractSync } from '../../actions/wallet/writeContractSync.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { BaseErrorType } from '../../errors/base.js'
import type { Chain } from '../../types/chain.js'
import type { GetEventArgs } from '../../types/contract.js'
import type { Log } from '../../types/log.js'
import type { Compute } from '../../types/utils.js'
import { parseEventLogs } from '../../utils/abi/parseEventLogs.js'
import * as Abis from '../Abis.js'
import type { AccessKeyAccount, resolveAccessKey } from '../Account.js'
import { signKeyAuthorization } from '../Account.js'
import * as Addresses from '../Addresses.js'
import * as Hardfork from '../Hardfork.js'
import type {
GetAccountParameter,
ReadParameters,
WriteParameters,
} from '../internal/types.js'
import { defineCall } from '../internal/utils.js'
import type { TransactionReceipt } from '../Transaction.js'
/** @internal */
const signatureTypes = {
0: 'secp256k1',
1: 'p256',
2: 'webAuthn',
} as const satisfies Record<number, string>
/** @internal */
const spendPolicies = {
true: 'limited',
false: 'unlimited',
} as const
/**
* Authorizes an access key by signing a key authorization and sending a transaction.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions, Account } from 'viem/tempo'
* import { generatePrivateKey } from 'viem/accounts'
*
* const account = Account.from({ privateKey: '0x...' })
* const client = createClient({
* account,
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* })
*
* const accessKey = Account.fromP256(generatePrivateKey(), {
* access: account,
* })
*
* const hash = await Actions.accessKey.authorize(client, {
* accessKey,
* expiry: Math.floor((Date.now() + 30_000) / 1000),
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function authorize<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: authorize.Parameters<chain, account>,
): Promise<authorize.ReturnValue> {
return authorize.inner(sendTransaction, client, parameters)
}
export namespace authorize {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = WriteParameters<chain, account> & Args
export type Args = {
/** The access key to authorize. */
accessKey: resolveAccessKey.Parameters
/** The chain ID. */
chainId?: number | undefined
/** Unix timestamp when the key expires. */
expiry?: number | undefined
/** Spending limits per token. */
limits?:
| { token: Address; limit: bigint; period?: number | undefined }[]
| undefined
/** Call scopes restricting which contracts/selectors this key can call. */
scopes?: KeyAuthorization.Scope[] | undefined
}
export type ReturnValue = WriteContractReturnType
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
/** @internal */
export async function inner<
action extends typeof sendTransaction | typeof sendTransactionSync,
chain extends Chain | undefined,
account extends Account | undefined,
>(
action: action,
client: Client<Transport, chain, account>,
parameters: authorize.Parameters<chain, account>,
): Promise<ReturnType<action>> {
const {
accessKey,
chainId = client.chain?.id,
expiry,
limits,
scopes,
...rest
} = parameters
const account_ = rest.account ?? client.account
if (!account_) throw new Error('account is required.')
if (!chainId) throw new Error('chainId is required.')
const parsed = parseAccount(account_)
const keyAuthorization = await signKeyAuthorization(parsed as never, {
chainId: BigInt(chainId),
key: accessKey,
expiry,
limits,
scopes,
})
return (await action(client, {
...rest,
keyAuthorization,
} as never)) as never
}
export function extractEvent(logs: Log[]) {
const [log] = parseEventLogs({
abi: Abis.accountKeychain,
logs,
eventName: 'KeyAuthorized',
strict: true,
})
if (!log) throw new Error('`KeyAuthorized` event not found.')
return log
}
}
/**
* Authorizes an access key and waits for the transaction receipt.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions, Account } from 'viem/tempo'
* import { generatePrivateKey } from 'viem/accounts'
*
* const account = Account.from({ privateKey: '0x...' })
* const client = createClient({
* account,
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* })
*
* const accessKey = Account.fromP256(generatePrivateKey(), {
* access: account,
* })
*
* const { receipt, ...result } = await Actions.accessKey.authorizeSync(client, {
* accessKey,
* expiry: Math.floor((Date.now() + 30_000) / 1000),
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and event data.
*/
export async function authorizeSync<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: authorizeSync.Parameters<chain, account>,
): Promise<authorizeSync.ReturnValue> {
const { throwOnReceiptRevert = true, ...rest } = parameters
const receipt = await authorize.inner(sendTransactionSync, client, {
...rest,
throwOnReceiptRevert,
} as never)
const { args } = authorize.extractEvent(receipt.logs)
return {
...args,
receipt,
} as never
}
export namespace authorizeSync {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = authorize.Parameters<chain, account>
export type Args = authorize.Args
export type ReturnValue = Compute<
GetEventArgs<
typeof Abis.accountKeychain,
'KeyAuthorized',
{ IndexedOnly: false; Required: true }
> & {
receipt: TransactionReceipt
}
>
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
}
/**
* Revokes an authorized access key.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* })
*
* const hash = await Actions.accessKey.revoke(client, {
* accessKey: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function revoke<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: revoke.Parameters<chain, account>,
): Promise<revoke.ReturnValue> {
return revoke.inner(writeContract, client, parameters)
}
export namespace revoke {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = WriteParameters<chain, account> & Args
export type Args = {
/** The access key to revoke. */
accessKey: Address | AccessKeyAccount
}
export type ReturnValue = WriteContractReturnType
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
/** @internal */
export async function inner<
action extends typeof writeContract | typeof writeContractSync,
chain extends Chain | undefined,
account extends Account | undefined,
>(
action: action,
client: Client<Transport, chain, account>,
parameters: revoke.Parameters<chain, account>,
): Promise<ReturnType<action>> {
const { accessKey, ...rest } = parameters
const call = revoke.call({ accessKey })
return (await action(client, {
...rest,
...call,
} as never)) as never
}
/**
* Defines a call to the `revokeKey` function.
*
* Can be passed as a parameter to:
* - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call
* - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call
* - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls
*
* @example
* ```ts
* import { createClient, http, walletActions } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* }).extend(walletActions)
*
* const hash = await client.sendTransaction({
* calls: [
* Actions.accessKey.revoke.call({ accessKey: '0x...' }),
* ],
* })
* ```
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { accessKey } = args
return defineCall({
address: Addresses.accountKeychain,
abi: Abis.accountKeychain,
functionName: 'revokeKey',
args: [resolveAccessKeyAddress(accessKey)],
})
}
export function extractEvent(logs: Log[]) {
const [log] = parseEventLogs({
abi: Abis.accountKeychain,
logs,
eventName: 'KeyRevoked',
strict: true,
})
if (!log) throw new Error('`KeyRevoked` event not found.')
return log
}
}
/**
* Revokes an authorized access key and waits for the transaction receipt.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* })
*
* const result = await Actions.accessKey.revokeSync(client, {
* accessKey: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and event data.
*/
export async function revokeSync<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: revokeSync.Parameters<chain, account>,
): Promise<revokeSync.ReturnValue> {
const { throwOnReceiptRevert = true, ...rest } = parameters
const receipt = await revoke.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
} as never)
const { args } = revoke.extractEvent(receipt.logs)
return {
...args,
receipt,
} as never
}
export namespace revokeSync {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = revoke.Parameters<chain, account>
export type Args = revoke.Args
export type ReturnValue = Compute<
GetEventArgs<
typeof Abis.accountKeychain,
'KeyRevoked',
{ IndexedOnly: false; Required: true }
> & {
receipt: TransactionReceipt
}
>
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
}
/**
* Updates the spending limit for a specific token on an authorized access key.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* })
*
* const hash = await Actions.accessKey.updateLimit(client, {
* accessKey: '0x...',
* token: '0x...',
* limit: 1000000000000000000n,
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function updateLimit<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: updateLimit.Parameters<chain, account>,
): Promise<updateLimit.ReturnValue> {
return updateLimit.inner(writeContract, client, parameters)
}
export namespace updateLimit {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = WriteParameters<chain, account> & Args
export type Args = {
/** The access key to update. */
accessKey: Address | AccessKeyAccount
/** The token address. */
token: Address
/** The new spending limit. */
limit: bigint
}
export type ReturnValue = WriteContractReturnType
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
/** @internal */
export async function inner<
action extends typeof writeContract | typeof writeContractSync,
chain extends Chain | undefined,
account extends Account | undefined,
>(
action: action,
client: Client<Transport, chain, account>,
parameters: updateLimit.Parameters<chain, account>,
): Promise<ReturnType<action>> {
const { accessKey, token, limit, ...rest } = parameters
const call = updateLimit.call({ accessKey, token, limit })
return (await action(client, {
...rest,
...call,
} as never)) as never
}
/**
* Defines a call to the `updateSpendingLimit` function.
*
* Can be passed as a parameter to:
* - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call
* - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call
* - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls
*
* @example
* ```ts
* import { createClient, http, walletActions } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* }).extend(walletActions)
*
* const hash = await client.sendTransaction({
* calls: [
* Actions.accessKey.updateLimit.call({
* accessKey: '0x...',
* token: '0x...',
* limit: 1000000000000000000n,
* }),
* ],
* })
* ```
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { accessKey, token, limit } = args
return defineCall({
address: Addresses.accountKeychain,
abi: Abis.accountKeychain,
functionName: 'updateSpendingLimit',
args: [resolveAccessKeyAddress(accessKey), token, limit],
})
}
export function extractEvent(logs: Log[]) {
const [log] = parseEventLogs({
abi: Abis.accountKeychain,
logs,
eventName: 'SpendingLimitUpdated',
strict: true,
})
if (!log) throw new Error('`SpendingLimitUpdated` event not found.')
return log
}
}
/**
* Updates the spending limit and waits for the transaction receipt.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* })
*
* const result = await Actions.accessKey.updateLimitSync(client, {
* accessKey: '0x...',
* token: '0x...',
* limit: 1000000000000000000n,
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and event data.
*/
export async function updateLimitSync<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: updateLimitSync.Parameters<chain, account>,
): Promise<updateLimitSync.ReturnValue> {
const { throwOnReceiptRevert = true, ...rest } = parameters
const receipt = await updateLimit.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
} as never)
const { args } = updateLimit.extractEvent(receipt.logs)
return {
account: args.account,
publicKey: args.publicKey,
token: args.token,
limit: args.newLimit,
receipt,
}
}
export namespace updateLimitSync {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = updateLimit.Parameters<chain, account>
export type Args = updateLimit.Args
export type ReturnValue = {
/** The account that owns the key. */
account: Address
/** The access key address. */
publicKey: Address
/** The token address. */
token: Address
/** The new spending limit. */
limit: bigint
/** The transaction receipt. */
receipt: TransactionReceipt
}
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
}
/**
* Gets access key information.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* })
*
* const key = await Actions.accessKey.getMetadata(client, {
* account: '0x...',
* accessKey: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The key information.
*/
export async function getMetadata<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: getMetadata.Parameters<account>,
): Promise<getMetadata.ReturnValue> {
const { account: account_ = client.account, accessKey, ...rest } = parameters
if (!account_) throw new Error('account is required.')
const account = parseAccount(account_)
const result = await readContract(client, {
...rest,
...getMetadata.call({ account: account.address, accessKey }),
})
return {
address: result.keyId,
keyType:
signatureTypes[result.signatureType as keyof typeof signatureTypes] ??
'secp256k1',
expiry: result.expiry,
spendPolicy: spendPolicies[`${result.enforceLimits}`],
isRevoked: result.isRevoked,
}
}
export namespace getMetadata {
export type Parameters<
account extends Account | undefined = Account | undefined,
> = ReadParameters & GetAccountParameter<account> & Pick<Args, 'accessKey'>
export type Args = {
/** Account address. */
account: Address
/** The access key. */
accessKey: Address | AccessKeyAccount
}
export type ReturnValue = {
/** The access key address. */
address: Address
/** The key type. */
keyType: 'secp256k1' | 'p256' | 'webAuthn'
/** The expiry timestamp. */
expiry: bigint
/** The spending policy. */
spendPolicy: 'limited' | 'unlimited'
/** Whether the key is revoked. */
isRevoked: boolean
}
/**
* Defines a call to the `getKey` function.
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { account, accessKey } = args
return defineCall({
address: Addresses.accountKeychain,
abi: Abis.accountKeychain,
functionName: 'getKey',
args: [account, resolveAccessKeyAddress(accessKey)],
})
}
}
/**
* Gets the remaining spending limit for a key-token pair.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* })
*
* const remaining = await Actions.accessKey.getRemainingLimit(client, {
* account: '0x...',
* accessKey: '0x...',
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The remaining spending amount.
*/
export async function getRemainingLimit<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: getRemainingLimit.Parameters<account>,
): Promise<getRemainingLimit.ReturnValue> {
const {
account: account_ = client.account,
accessKey,
token,
...rest
} = parameters
if (!account_) throw new Error('account is required.')
const account = parseAccount(account_)
// TODO: remove pre-t3 branch once mainnet is on t3.
const hardfork = (client.chain as { hardfork?: string } | undefined)?.hardfork
if (hardfork && Hardfork.lt(hardfork, 't3')) {
const remaining = await readContract(client, {
...rest,
...getRemainingLimit.call({ account: account.address, accessKey, token }),
})
return { remaining, periodEnd: undefined }
}
const [remaining, periodEnd] = await readContract(client, {
...rest,
...getRemainingLimit.callWithPeriod({
account: account.address,
accessKey,
token,
}),
})
return { remaining, periodEnd }
}
export namespace getRemainingLimit {
export type Parameters<
account extends Account | undefined = Account | undefined,
> = ReadParameters &
GetAccountParameter<account> &
Pick<Args, 'accessKey' | 'token'>
export type Args = {
/** Account address. */
account: Address
/** The access key. */
accessKey: Address | AccessKeyAccount
/** The token address. */
token: Address
}
export type ReturnValue = {
remaining: bigint
periodEnd: bigint | undefined
}
/**
* Defines a call to the `getRemainingLimit` function (pre-T3).
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { account, accessKey, token } = args
return defineCall({
address: Addresses.accountKeychain,
abi: Abis.accountKeychain,
functionName: 'getRemainingLimit',
args: [account, resolveAccessKeyAddress(accessKey), token],
})
}
/**
* Defines a call to the `getRemainingLimitWithPeriod` function (T3+).
*
* @param args - Arguments.
* @returns The call.
*/
export function callWithPeriod(args: Args) {
const { account, accessKey, token } = args
return defineCall({
address: Addresses.accountKeychain,
abi: Abis.accountKeychain,
functionName: 'getRemainingLimitWithPeriod',
args: [account, resolveAccessKeyAddress(accessKey), token],
})
}
}
/**
* Signs a key authorization for an access key.
*
* @example
* ```ts
* import { generatePrivateKey } from 'viem/accounts'
* import { Account, Actions } from 'viem/tempo'
*
* const account = Account.from({ privateKey: '0x...' })
* const accessKey = Account.fromP256(generatePrivateKey(), {
* access: account,
* })
*
* const keyAuthorization = await Actions.accessKey.signAuthorization(
* client,
* {
* account,
* accessKey,
* expiry: Math.floor((Date.now() + 30_000) / 1000),
* },
* )
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The signed key authorization.
*/
export async function signAuthorization<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: signAuthorization.Parameters<account>,
): Promise<signAuthorization.ReturnValue> {
const { accessKey, chainId = client.chain?.id, ...rest } = parameters
const account_ = rest.account ?? client.account
if (!account_) throw new Error('account is required.')
if (!chainId) throw new Error('chainId is required.')
const parsed = parseAccount(account_)
return signKeyAuthorization(parsed as never, {
chainId: BigInt(chainId),
key: accessKey,
...rest,
})
}
export namespace signAuthorization {
export type Parameters<
account extends Account | undefined = Account | undefined,
> = GetAccountParameter<account> & {
/** The access key to authorize. */
accessKey: resolveAccessKey.Parameters
/** The chain ID. */
chainId?: number | undefined
/** Unix timestamp when the key expires. */
expiry?: number | undefined
/** Spending limits per token. */
limits?:
| { token: Address; limit: bigint; period?: number | undefined }[]
| undefined
/** Call scopes restricting which contracts/selectors this key can call. */
scopes?: KeyAuthorization.Scope[] | undefined
}
export type ReturnValue = Awaited<ReturnType<typeof signKeyAuthorization>>
}
/** @internal */
function resolveAccessKeyAddress(
accessKey: Address | AccessKeyAccount,
): Address {
if (typeof accessKey === 'string') return accessKey
return accessKey.accessKeyAddress
}

1119
node_modules/viem/tempo/actions/amm.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

2352
node_modules/viem/tempo/actions/dex.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

119
node_modules/viem/tempo/actions/faucet.ts generated vendored Normal file
View File

@@ -0,0 +1,119 @@
import type { Address } from 'abitype'
import type { Account } from '../../accounts/types.js'
import { parseAccount } from '../../accounts/utils/parseAccount.js'
import { waitForTransactionReceipt } from '../../actions/public/waitForTransactionReceipt.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 type { TransactionReceipt } from '../Transaction.js'
/**
* Funds an account with an initial amount of set token(s)
* on Tempo's testnet.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* })
*
* const hashes = await Actions.faucet.fund(client, {
* account: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function fund<chain extends Chain | undefined>(
client: Client<Transport, chain>,
parameters: fund.Parameters,
): Promise<fund.ReturnValue> {
const account = parseAccount(parameters.account)
return client.request<{
Method: 'tempo_fundAddress'
Parameters: [address: Address]
ReturnType: readonly Hash[]
}>({
method: 'tempo_fundAddress',
params: [account.address],
})
}
export declare namespace fund {
export type Parameters = {
/** Account to fund. */
account: Account | Address
}
export type ReturnValue = readonly Hash[]
}
/**
* Funds an account with an initial amount of set token(s)
* on Tempo's testnet. Waits for the transactions to be included
* on a block before returning a response.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* })
*
* const hashes = await Actions.faucet.fundSync(client, {
* account: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function fundSync<chain extends Chain | undefined>(
client: Client<Transport, chain>,
parameters: fundSync.Parameters,
): Promise<fundSync.ReturnValue> {
const { timeout = 10_000 } = parameters
const account = parseAccount(parameters.account)
const hashes = await client.request<{
Method: 'tempo_fundAddress'
Parameters: [address: Address]
ReturnType: readonly Hash[]
}>({
method: 'tempo_fundAddress',
params: [account.address],
})
const receipts = await Promise.all(
hashes.map((hash) =>
waitForTransactionReceipt(client, {
hash,
checkReplacement: false,
timeout,
}),
),
)
return receipts
}
export declare namespace fundSync {
export type Parameters = {
/** Account to fund. */
account: Account | Address
/** Timeout. */
timeout?: number | undefined
}
export type ReturnValue = readonly TransactionReceipt[]
}

702
node_modules/viem/tempo/actions/fee.ts generated vendored Normal file
View File

@@ -0,0 +1,702 @@
import type { Address } from 'abitype'
import { TokenId } from 'ox/tempo'
import type { Account } from '../../accounts/types.js'
import { parseAccount } from '../../accounts/utils/parseAccount.js'
import { readContract } from '../../actions/public/readContract.js'
import type { WatchContractEventParameters } from '../../actions/public/watchContractEvent.js'
import { watchContractEvent } from '../../actions/public/watchContractEvent.js'
import type { WriteContractReturnType } from '../../actions/wallet/writeContract.js'
import { writeContract } from '../../actions/wallet/writeContract.js'
import { writeContractSync } from '../../actions/wallet/writeContractSync.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { zeroAddress } from '../../constants/address.js'
import type { BaseErrorType } from '../../errors/base.js'
import type { Chain } from '../../types/chain.js'
import type { ExtractAbiItem, GetEventArgs } from '../../types/contract.js'
import type { Log, Log as viem_Log } from '../../types/log.js'
import type { Compute, UnionOmit } from '../../types/utils.js'
import { parseEventLogs } from '../../utils/abi/parseEventLogs.js'
import * as Abis from '../Abis.js'
import * as Addresses from '../Addresses.js'
import type {
GetAccountParameter,
ReadParameters,
WriteParameters,
} from '../internal/types.js'
import { defineCall } from '../internal/utils.js'
import type { TransactionReceipt } from '../Transaction.js'
/**
* Gets the user's default fee token.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const { address, id } = await Actions.fee.getUserToken(client)
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function getUserToken<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
...parameters: account extends Account
? [getUserToken.Parameters<account>] | []
: [getUserToken.Parameters<account>]
): Promise<getUserToken.ReturnValue> {
const { account: account_ = client.account, ...rest } = parameters[0] ?? {}
if (!account_) throw new Error('account is required.')
const account = parseAccount(account_)
const address = await readContract(client, {
...rest,
...getUserToken.call({ account: account.address }),
})
if (address === zeroAddress) return null
return {
address,
id: TokenId.fromAddress(address),
}
}
export namespace getUserToken {
export type Parameters<
account extends Account | undefined = Account | undefined,
> = ReadParameters & GetAccountParameter<account>
export type Args = {
/** Account address. */
account: Address
}
export type ReturnValue = Compute<{
address: Address
id: bigint
} | null>
/**
* Defines a call to the `userTokens` function.
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { account } = args
return defineCall({
address: Addresses.feeManager,
abi: Abis.feeManager,
args: [account],
functionName: 'userTokens',
})
}
}
/**
* Sets the user's default fee token.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const hash = await Actions.fee.setUserToken(client, {
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function setUserToken<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: setUserToken.Parameters<chain, account>,
): Promise<setUserToken.ReturnValue> {
return setUserToken.inner(writeContract, client, parameters)
}
export namespace setUserToken {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = WriteParameters<chain, account> & Args
export type Args = {
/** Address or ID of the TIP20 token. */
token: TokenId.TokenIdOrAddress
}
export type ReturnValue = WriteContractReturnType
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
/** @internal */
export async function inner<
action extends typeof writeContract | typeof writeContractSync,
chain extends Chain | undefined,
account extends Account | undefined,
>(
action: action,
client: Client<Transport, chain, account>,
parameters: setUserToken.Parameters<chain, account>,
): Promise<ReturnType<action>> {
const { token, ...rest } = parameters
const call = setUserToken.call({ token })
return (await action(client, {
...rest,
...call,
} as never)) as never
}
/**
* Defines a call to the `setUserToken` function.
*
* Can be passed as a parameter to:
* - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call
* - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call
* - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls
*
* @example
* ```ts
* import { createClient, http, walletActions } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* }).extend(walletActions)
*
* const { result } = await client.sendCalls({
* calls: [
* actions.fee.setUserToken.call({
* token: '0x20c0...beef',
* }),
* actions.fee.setUserToken.call({
* token: '0x20c0...babe',
* }),
* ]
* })
* ```
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { token } = args
return defineCall({
address: Addresses.feeManager,
abi: Abis.feeManager,
functionName: 'setUserToken',
args: [TokenId.toAddress(token)],
})
}
export function extractEvent(logs: Log[]) {
const [log] = parseEventLogs({
abi: Abis.feeManager,
logs,
eventName: 'UserTokenSet',
strict: true,
})
if (!log) throw new Error('`UserTokenSet` event not found.')
return log
}
}
/**
* Sets the user's default fee token.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const result = await Actions.fee.setUserTokenSync(client, {
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and event data.
*/
export async function setUserTokenSync<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: setUserTokenSync.Parameters<chain, account>,
): Promise<setUserTokenSync.ReturnValue> {
const { throwOnReceiptRevert = true, ...rest } = parameters
const receipt = await setUserToken.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
} as never)
const { args } = setUserToken.extractEvent(receipt.logs)
return {
...args,
receipt,
} as never
}
export namespace setUserTokenSync {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = setUserToken.Parameters<chain, account>
export type Args = setUserToken.Args
export type ReturnValue = Compute<
GetEventArgs<
typeof Abis.feeManager,
'UserTokenSet',
{ IndexedOnly: false; Required: true }
> & {
receipt: TransactionReceipt
}
>
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
}
/**
* Watches for user token set events.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const unwatch = actions.fee.watchSetUserToken(client, {
* onUserTokenSet: (args, log) => {
* console.log('User token set:', args)
* },
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns A function to unsubscribe from the event.
*/
export function watchSetUserToken<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: watchSetUserToken.Parameters,
) {
const { onUserTokenSet, ...rest } = parameters
return watchContractEvent(client, {
...rest,
address: Addresses.feeManager,
abi: Abis.feeManager,
eventName: 'UserTokenSet',
onLogs: (logs) => {
for (const log of logs) onUserTokenSet(log.args, log)
},
strict: true,
})
}
export declare namespace watchSetUserToken {
export type Args = GetEventArgs<
typeof Abis.feeManager,
'UserTokenSet',
{ IndexedOnly: false; Required: true }
>
export type Log = viem_Log<
bigint,
number,
false,
ExtractAbiItem<typeof Abis.feeManager, 'UserTokenSet'>,
true
>
export type Parameters = UnionOmit<
WatchContractEventParameters<typeof Abis.feeManager, 'UserTokenSet', true>,
'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'
> & {
/** Callback to invoke when a user token is set. */
onUserTokenSet: (args: Args, log: Log) => void
}
}
/**
* Gets the validator's preferred fee token.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const { address, id } = await Actions.fee.getValidatorToken(client, {
* validator: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The validator's preferred fee token, or null if not set.
*/
export async function getValidatorToken<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: getValidatorToken.Parameters,
): Promise<getValidatorToken.ReturnValue> {
const { validator, ...rest } = parameters
const address = await readContract(client, {
...rest,
...getValidatorToken.call({ validator }),
})
if (address === zeroAddress) return null
return {
address,
id: TokenId.fromAddress(address),
}
}
export namespace getValidatorToken {
export type Parameters = ReadParameters & Args
export type Args = {
/** Validator address. */
validator: Address
}
export type ReturnValue = Compute<{
address: Address
id: bigint
} | null>
/**
* Defines a call to the `validatorTokens` function.
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { validator } = args
return defineCall({
address: Addresses.feeManager,
abi: Abis.feeManager,
args: [validator],
functionName: 'validatorTokens',
})
}
}
/**
* Sets the validator's preferred fee token.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const hash = await Actions.fee.setValidatorToken(client, {
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function setValidatorToken<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: setValidatorToken.Parameters<chain, account>,
): Promise<setValidatorToken.ReturnValue> {
return setValidatorToken.inner(writeContract, client, parameters)
}
export namespace setValidatorToken {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = WriteParameters<chain, account> & Args
export type Args = {
/** Address or ID of the TIP20 token. */
token: TokenId.TokenIdOrAddress
}
export type ReturnValue = WriteContractReturnType
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
/** @internal */
export async function inner<
action extends typeof writeContract | typeof writeContractSync,
chain extends Chain | undefined,
account extends Account | undefined,
>(
action: action,
client: Client<Transport, chain, account>,
parameters: setValidatorToken.Parameters<chain, account>,
): Promise<ReturnType<action>> {
const { token, ...rest } = parameters
const call = setValidatorToken.call({ token })
return (await action(client, {
...rest,
...call,
} as never)) as never
}
/**
* Defines a call to the `setValidatorToken` function.
*
* Can be passed as a parameter to:
* - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call
* - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call
* - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls
*
* @example
* ```ts
* import { createClient, http, walletActions } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* }).extend(walletActions)
*
* const { result } = await client.sendCalls({
* calls: [
* actions.fee.setValidatorToken.call({
* token: '0x20c0...beef',
* }),
* actions.fee.setValidatorToken.call({
* token: '0x20c0...babe',
* }),
* ]
* })
* ```
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { token } = args
return defineCall({
address: Addresses.feeManager,
abi: Abis.feeManager,
functionName: 'setValidatorToken',
args: [TokenId.toAddress(token)],
})
}
export function extractEvent(logs: Log[]) {
const [log] = parseEventLogs({
abi: Abis.feeManager,
logs,
eventName: 'ValidatorTokenSet',
strict: true,
})
if (!log) throw new Error('`ValidatorTokenSet` event not found.')
return log
}
}
/**
* Sets the validator's preferred fee token.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const result = await Actions.fee.setValidatorTokenSync(client, {
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and event data.
*/
export async function setValidatorTokenSync<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: setValidatorTokenSync.Parameters<chain, account>,
): Promise<setValidatorTokenSync.ReturnValue> {
const { throwOnReceiptRevert = true, ...rest } = parameters
const receipt = await setValidatorToken.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
} as never)
const { args } = setValidatorToken.extractEvent(receipt.logs)
return {
...args,
receipt,
} as never
}
export namespace setValidatorTokenSync {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = setValidatorToken.Parameters<chain, account>
export type Args = setValidatorToken.Args
export type ReturnValue = Compute<
GetEventArgs<
typeof Abis.feeManager,
'ValidatorTokenSet',
{ IndexedOnly: false; Required: true }
> & {
receipt: TransactionReceipt
}
>
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
}
/**
* Watches for validator token set events.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const unwatch = actions.fee.watchSetValidatorToken(client, {
* onValidatorTokenSet: (args, log) => {
* console.log('Validator token set:', args)
* },
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns A function to unsubscribe from the event.
*/
export function watchSetValidatorToken<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: watchSetValidatorToken.Parameters,
) {
const { onValidatorTokenSet, ...rest } = parameters
return watchContractEvent(client, {
...rest,
address: Addresses.feeManager,
abi: Abis.feeManager,
eventName: 'ValidatorTokenSet',
onLogs: (logs) => {
for (const log of logs) onValidatorTokenSet(log.args, log)
},
strict: true,
})
}
export declare namespace watchSetValidatorToken {
export type Args = GetEventArgs<
typeof Abis.feeManager,
'ValidatorTokenSet',
{ IndexedOnly: false; Required: true }
>
export type Log = viem_Log<
bigint,
number,
false,
ExtractAbiItem<typeof Abis.feeManager, 'ValidatorTokenSet'>,
true
>
export type Parameters = UnionOmit<
WatchContractEventParameters<
typeof Abis.feeManager,
'ValidatorTokenSet',
true
>,
'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'
> & {
/** Callback to invoke when a validator token is set. */
onValidatorTokenSet: (args: Args, log: Log) => void
}
}

14
node_modules/viem/tempo/actions/index.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
// biome-ignore lint/performance/noBarrelFile: _
export * as accessKey from './accessKey.js'
export * as amm from './amm.js'
export * as dex from './dex.js'
export * as faucet from './faucet.js'
export * as fee from './fee.js'
export * as nonce from './nonce.js'
export * as policy from './policy.js'
export * as reward from './reward.js'
export * as simulate from './simulate.js'
export * as token from './token.js'
export * as validator from './validator.js'
export * as virtualAddress from './virtualAddress.js'
export * as zone from './zone.js'

155
node_modules/viem/tempo/actions/nonce.ts generated vendored Normal file
View File

@@ -0,0 +1,155 @@
import type { Address } from 'abitype'
import type { Account } from '../../accounts/types.js'
import type { ReadContractReturnType } from '../../actions/public/readContract.js'
import { readContract } from '../../actions/public/readContract.js'
import type { WatchContractEventParameters } from '../../actions/public/watchContractEvent.js'
import { watchContractEvent } from '../../actions/public/watchContractEvent.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 { ExtractAbiItem, GetEventArgs } from '../../types/contract.js'
import type { Log as viem_Log } from '../../types/log.js'
import type { UnionOmit } from '../../types/utils.js'
import * as Abis from '../Abis.js'
import * as Addresses from '../Addresses.js'
import type { ReadParameters } from '../internal/types.js'
import { defineCall } from '../internal/utils.js'
/**
* Gets the nonce for an account and nonce key.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* })
*
* const nonce = await Actions.nonce.getNonce(client, {
* account: '0x...',
* nonceKey: 1n,
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The nonce value.
*/
export async function getNonce<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: getNonce.Parameters,
): Promise<getNonce.ReturnValue> {
const { account, nonceKey, ...rest } = parameters
return readContract(client, {
...rest,
...getNonce.call({ account, nonceKey }),
})
}
export namespace getNonce {
export type Parameters = ReadParameters & Args
export type Args = {
/** Account address. */
account: Address
/** Nonce key (must be > 0, key 0 is reserved for protocol nonces). */
nonceKey: bigint
}
export type ReturnValue = ReadContractReturnType<
typeof Abis.nonce,
'getNonce',
never
>
/**
* Defines a call to the `getNonce` function.
*
* Can be passed as a parameter to:
* - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call
* - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call
* - [`multicall`](https://viem.sh/docs/contract/multicall): execute multiple calls in parallel
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' }),
* transport: http(),
* })
*
* const result = await client.multicall({
* contracts: [
* Actions.nonce.getNonce.call({ account: '0x...', nonceKey: 1n }),
* Actions.nonce.getNonce.call({ account: '0x...', nonceKey: 2n }),
* ],
* })
* ```
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { account, nonceKey } = args
return defineCall({
address: Addresses.nonceManager,
abi: Abis.nonce,
args: [account, nonceKey],
functionName: 'getNonce',
})
}
}
export function watchNonceIncremented<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: watchNonceIncremented.Parameters,
) {
const { onNonceIncremented, ...rest } = parameters
return watchContractEvent(client, {
...rest,
address: Addresses.nonceManager,
abi: Abis.nonce,
eventName: 'NonceIncremented',
onLogs: (logs) => {
for (const log of logs) onNonceIncremented(log.args, log)
},
strict: true,
})
}
export declare namespace watchNonceIncremented {
export type Args = GetEventArgs<
typeof Abis.nonce,
'NonceIncremented',
{ IndexedOnly: false; Required: true }
>
export type Log = viem_Log<
bigint,
number,
false,
ExtractAbiItem<typeof Abis.nonce, 'NonceIncremented'>,
true
>
export type Parameters = UnionOmit<
WatchContractEventParameters<typeof Abis.nonce, 'NonceIncremented', true>,
'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'
> & {
/** Callback to invoke when a nonce is incremented. */
onNonceIncremented: (args: Args, log: Log) => void
}
}

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

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

1329
node_modules/viem/tempo/actions/policy.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

993
node_modules/viem/tempo/actions/reward.ts generated vendored Normal file
View File

@@ -0,0 +1,993 @@
import type { Address } from 'abitype'
import type { Account } from '../../accounts/types.js'
import type { ReadContractReturnType } from '../../actions/public/readContract.js'
import { readContract } from '../../actions/public/readContract.js'
import type {
WatchContractEventParameters,
WatchContractEventReturnType,
} from '../../actions/public/watchContractEvent.js'
import { watchContractEvent } from '../../actions/public/watchContractEvent.js'
import type { WriteContractReturnType } from '../../actions/wallet/writeContract.js'
import { writeContract } from '../../actions/wallet/writeContract.js'
import { writeContractSync } from '../../actions/wallet/writeContractSync.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { BaseErrorType } from '../../errors/base.js'
import type { Chain } from '../../types/chain.js'
import type { ExtractAbiItem, GetEventArgs } from '../../types/contract.js'
import type { Log, Log as viem_Log } from '../../types/log.js'
import type { UnionOmit } from '../../types/utils.js'
import { parseEventLogs } from '../../utils/abi/parseEventLogs.js'
import * as Abis from '../Abis.js'
import type { ReadParameters, WriteParameters } from '../internal/types.js'
import { defineCall } from '../internal/utils.js'
/**
* Claims accumulated rewards for a recipient.
*
* This function allows a reward recipient to claim their accumulated rewards
* and receive them as token transfers to their own balance.
*
* - Accrues all pending rewards up to the current block timestamp.
* - Updates the caller's reward accounting.
* - Transfers the caller's accumulated `rewardBalance` from the token contract to the caller.
* - If the contract's balance is insufficient, claims up to the available amount.
* - Returns the actual amount claimed.
*
* Notes:
* - Reverts with `Paused` if the token is paused.
* - Reverts with `PolicyForbids` if the caller is not authorized to receive tokens under TIP-403.
* - If opted in, the claimed amount is added back to `optedInSupply` since it goes to the recipient's balance.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const hash = await Actions.reward.claim(client, {
* token: '0x20c0000000000000000000000000000000000001',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function claim<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: claim.Parameters<chain, account>,
): Promise<claim.ReturnValue> {
return claim.inner(writeContract, client, parameters)
}
export namespace claim {
export type Args = {
/** The TIP20 token address */
token: Address
}
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = WriteParameters<chain, account> & Args
export type ReturnValue = WriteContractReturnType
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
/** @internal */
export async function inner<
action extends typeof writeContract | typeof writeContractSync,
chain extends Chain | undefined,
account extends Account | undefined,
>(
action: action,
client: Client<Transport, chain, account>,
parameters: Parameters<chain, account>,
): Promise<ReturnType<action>> {
const { token, ...rest } = parameters
const call = claim.call({ token })
return (await action(client, {
...rest,
...call,
} as never)) as never
}
/**
* Defines a call to the `claimRewards` function.
*
* Can be passed as a parameter to:
* - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call
* - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call
* - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls
*
* @example
* ```ts
* import { createClient, http, walletActions } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* }).extend(walletActions)
*
* const hash = await client.sendTransaction({
* calls: [actions.reward.claim.call({
* token: '0x20c0000000000000000000000000000000000001',
* })],
* })
* ```
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { token } = args
return defineCall({
address: token,
abi: Abis.tip20,
args: [],
functionName: 'claimRewards',
})
}
}
/**
* Claims accumulated rewards for a recipient and waits for confirmation.
*
* This function allows a reward recipient to claim their accumulated rewards
* and receive them as token transfers to their own balance.
*
* Behavior:
* - Accrues all pending rewards up to the current block timestamp.
* - Updates the caller's reward accounting.
* - Transfers the caller's accumulated `rewardBalance` from the token contract to the caller.
* - If the contract's balance is insufficient, claims up to the available amount.
*
* Notes:
* - Reverts with `Paused` if the token is paused.
* - Reverts with `PolicyForbids` if the caller is not authorized to receive tokens under TIP-403.
* - If opted in, the claimed amount is added back to `optedInSupply` since it goes to the recipient's balance.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const { receipt } = await Actions.reward.claimSync(client, {
* token: '0x20c0000000000000000000000000000000000001',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The amount claimed and transaction receipt.
*/
export async function claimSync<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: claimSync.Parameters<chain, account>,
): Promise<claimSync.ReturnValue> {
const { throwOnReceiptRevert = true, ...rest } = parameters
const receipt = await claim.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
} as never)
return {
receipt,
} as never
}
export namespace claimSync {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = WriteParameters<chain, account> & claim.Args
export type ReturnValue = {
/** The transaction receipt */
receipt: Awaited<ReturnType<typeof writeContractSync>>
}
export type ErrorType = claim.ErrorType
}
/**
* Distributes rewards to opted-in token holders.
*
* This function transfers `amount` of tokens from the caller into the token contract's
* reward pool and immediately distributes them to current opted-in holders by increasing
* `globalRewardPerToken`.
*
* Notes:
* - Reverts with `InvalidAmount` if `amount == 0`.
* - The transfer from caller to pool is subject to TIP-403 policy checks.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const hash = await Actions.reward.distribute(client, {
* amount: 100000000000000000000n,
* token: '0x20c0000000000000000000000000000000000001',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function distribute<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: distribute.Parameters<chain, account>,
): Promise<distribute.ReturnValue> {
return distribute.inner(writeContract, client, parameters)
}
/**
* Distributes rewards to opted-in token holders and waits for confirmation.
*
* This function transfers `amount` of tokens from the caller into the token contract's
* reward pool and immediately distributes them to current opted-in holders by increasing
* `globalRewardPerToken`.
*
* Notes:
* - Reverts with `InvalidAmount` if `amount == 0`.
* - The transfer from caller to pool is subject to TIP-403 policy checks.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const { amount, funder, receipt } = await Actions.reward.distributeSync(client, {
* amount: 100000000000000000000n,
* token: '0x20c0000000000000000000000000000000000001',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The funder, amount, and transaction receipt.
*/
export async function distributeSync<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: distributeSync.Parameters<chain, account>,
): Promise<distributeSync.ReturnValue> {
const { throwOnReceiptRevert = true, ...rest } = parameters
const receipt = await distribute.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
} as never)
const { args } = distribute.extractEvent(receipt.logs)
return {
...args,
receipt,
} as never
}
export namespace distribute {
export type Args = {
/** The amount of tokens to distribute (must be > 0) */
amount: bigint
/** The TIP20 token address */
token: Address
}
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = WriteParameters<chain, account> & Args
export type ReturnValue = WriteContractReturnType
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
/** @internal */
export async function inner<
action extends typeof writeContract | typeof writeContractSync,
chain extends Chain | undefined,
account extends Account | undefined,
>(
action: action,
client: Client<Transport, chain, account>,
parameters: Parameters<chain, account>,
): Promise<ReturnType<action>> {
const { amount, token, ...rest } = parameters
const call = distribute.call({ amount, token })
return (await action(client, {
...rest,
...call,
} as never)) as never
}
/**
* Defines a call to the `distributeReward` function.
*
* Can be passed as a parameter to:
* - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call
* - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call
* - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls
*
* @example
* ```ts
* import { createClient, http, walletActions } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* }).extend(walletActions)
*
* const hash = await client.sendTransaction({
* calls: [actions.reward.distribute.call({
* amount: 100000000000000000000n,
* token: '0x20c0000000000000000000000000000000000001',
* })],
* })
* ```
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { amount, token } = args
return defineCall({
address: token,
abi: Abis.tip20,
args: [amount],
functionName: 'distributeReward',
})
}
/**
* Extracts the `RewardDistributed` event from logs.
*
* @param logs - The logs.
* @returns The `RewardDistributed` event.
*/
export function extractEvent(logs: Log[]) {
const [log] = parseEventLogs({
abi: Abis.tip20,
logs,
eventName: 'RewardDistributed',
strict: true,
})
if (!log) throw new Error('`RewardDistributed` event not found.')
return log
}
}
export declare namespace distributeSync {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = WriteParameters<chain, account> & distribute.Args
export type ReturnValue = {
/** The amount distributed */
amount: bigint
/** The address that funded the distribution */
funder: Address
/** The transaction receipt */
receipt: Awaited<ReturnType<typeof writeContractSync>>
}
export type ErrorType = distribute.ErrorType
}
/**
* Gets the global reward per token value.
*
* Returns the current global reward per token value scaled by `ACC_PRECISION` (1e18).
* This value increases each time rewards are distributed.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const rewardPerToken = await Actions.reward.getGlobalRewardPerToken(client, {
* token: '0x20c0000000000000000000000000000000000001',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The global reward per token (scaled by 1e18).
*/
export async function getGlobalRewardPerToken<chain extends Chain | undefined>(
client: Client<Transport, chain>,
parameters: getGlobalRewardPerToken.Parameters,
): Promise<getGlobalRewardPerToken.ReturnValue> {
return readContract(client, {
...parameters,
...getGlobalRewardPerToken.call(parameters),
})
}
export namespace getGlobalRewardPerToken {
export type Parameters = ReadParameters & Args
export type Args = {
/** The TIP20 token address */
token: Address
}
export type ReturnValue = ReadContractReturnType<
typeof Abis.tip20,
'globalRewardPerToken',
never
>
/**
* Defines a call to the `globalRewardPerToken` function.
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { token } = args
return defineCall({
address: token,
abi: Abis.tip20,
args: [],
functionName: 'globalRewardPerToken',
})
}
}
/**
* Calculates the pending claimable rewards for an account without modifying state.
*
* Returns the total pending claimable reward amount, including stored balance and newly accrued rewards.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const pending = await Actions.reward.getPendingRewards(client, {
* token: '0x20c0000000000000000000000000000000000001',
* account: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The total pending claimable reward amount.
*/
export async function getPendingRewards<chain extends Chain | undefined>(
client: Client<Transport, chain>,
parameters: getPendingRewards.Parameters,
): Promise<getPendingRewards.ReturnValue> {
return readContract(client, {
...parameters,
...getPendingRewards.call(parameters),
})
}
export namespace getPendingRewards {
export type Parameters = ReadParameters & Args
export type Args = {
/** The account address to query pending rewards for */
account: Address
/** The TIP20 token address */
token: Address
}
export type ReturnValue = ReadContractReturnType<
typeof Abis.tip20,
'getPendingRewards',
never
>
/**
* Defines a call to the `getPendingRewards` function.
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { account, token } = args
return defineCall({
address: token,
abi: Abis.tip20,
args: [account],
functionName: 'getPendingRewards',
})
}
}
/**
* Gets the reward information for a specific account.
*
* Returns the reward recipient address, reward per token value, and accumulated reward balance for the specified account.
* This information includes:
* - `rewardRecipient`: The address designated to receive rewards (zero address if opted out)
* - `rewardPerToken`: The reward per token value for this account
* - `rewardBalance`: The accumulated reward balance waiting to be claimed
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const info = await Actions.reward.getUserRewardInfo(client, {
* token: '0x20c0000000000000000000000000000000000001',
* account: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The user's reward information (recipient, rewardPerToken, rewardBalance).
*/
export async function getUserRewardInfo<chain extends Chain | undefined>(
client: Client<Transport, chain>,
parameters: getUserRewardInfo.Parameters,
): Promise<getUserRewardInfo.ReturnValue> {
return readContract(client, {
...parameters,
...getUserRewardInfo.call(parameters),
})
}
export namespace getUserRewardInfo {
export type Parameters = ReadParameters & Args
export type Args = {
/** The account address to query reward info for */
account: Address
/** The TIP20 token address */
token: Address
}
export type ReturnValue = ReadContractReturnType<
typeof Abis.tip20,
'userRewardInfo',
never
>
/**
* Defines a call to the `userRewardInfo` function.
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { account, token } = args
return defineCall({
address: token,
abi: Abis.tip20,
args: [account],
functionName: 'userRewardInfo',
})
}
}
/**
* Sets or changes the reward recipient for a token holder.
*
* This function allows a token holder to designate who should receive their share of rewards:
* - If `recipient` is the zero address, opts out from rewards distribution.
* - Otherwise, opts in and sets `recipient` as the address that will receive accrued rewards.
* - Can be called with `recipient == msg.sender` to receive rewards directly.
* - Automatically distributes any accrued rewards to the current recipient before changing.
*
* TIP-403 Policy:
* - Reverts with `PolicyForbids` if `recipient` is not the zero address and either the holder or recipient is not authorized to receive tokens under the token's transfer policy.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const hash = await Actions.reward.setRecipient(client, {
* recipient: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',
* token: '0x20c0000000000000000000000000000000000001',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function setRecipient<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: setRecipient.Parameters<chain, account>,
): Promise<setRecipient.ReturnValue> {
return setRecipient.inner(writeContract, client, parameters)
}
/**
* Sets or changes the reward recipient for a token holder and waits for confirmation.
*
* This function allows a token holder to designate who should receive their share of rewards:
* - If `recipient` is the zero address, opts out from rewards distribution.
* - Otherwise, opts in and sets `recipient` as the address that will receive accrued rewards.
* - Can be called with `recipient == msg.sender` to receive rewards directly.
* - Automatically distributes any accrued rewards to the current recipient before changing.
*
* TIP-403 Policy:
* - Reverts with `PolicyForbids` if `recipient` is not the zero address and either the holder or recipient is not authorized to receive tokens under the token's transfer policy.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const { holder, recipient, receipt } = await Actions.reward.setRecipientSync(client, {
* recipient: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',
* token: '0x20c0000000000000000000000000000000000001',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The holder, recipient, and transaction receipt.
*/
export async function setRecipientSync<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: setRecipientSync.Parameters<chain, account>,
): Promise<setRecipientSync.ReturnValue> {
const { throwOnReceiptRevert = true, ...rest } = parameters
const receipt = await setRecipient.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
} as never)
const { args } = setRecipient.extractEvent(receipt.logs)
return {
...args,
receipt,
} as never
}
export namespace setRecipient {
export type Args = {
/** The reward recipient address (use zero address to opt out of rewards) */
recipient: Address
/** The TIP20 token address */
token: Address
}
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = WriteParameters<chain, account> & Args
export type ReturnValue = WriteContractReturnType
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
/** @internal */
export async function inner<
action extends typeof writeContract | typeof writeContractSync,
chain extends Chain | undefined,
account extends Account | undefined,
>(
action: action,
client: Client<Transport, chain, account>,
parameters: Parameters<chain, account>,
): Promise<ReturnType<action>> {
const { recipient, token, ...rest } = parameters
const call = setRecipient.call({ recipient, token })
return (await action(client, {
...rest,
...call,
} as never)) as never
}
/**
* Defines a call to the `setRewardRecipient` function.
*
* Can be passed as a parameter to:
* - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call
* - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call
* - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls
*
* @example
* ```ts
* import { createClient, http, walletActions } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* }).extend(walletActions)
*
* const hash = await client.sendTransaction({
* calls: [actions.reward.setRecipient.call({
* recipient: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',
* token: '0x20c0000000000000000000000000000000000001',
* })],
* })
* ```
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { recipient, token } = args
return defineCall({
address: token,
abi: Abis.tip20,
args: [recipient],
functionName: 'setRewardRecipient',
})
}
/**
* Extracts the `RewardRecipientSet` event from logs.
*
* @param logs - The logs.
* @returns The `RewardRecipientSet` event.
*/
export function extractEvent(logs: Log[]) {
const [log] = parseEventLogs({
abi: Abis.tip20,
logs,
eventName: 'RewardRecipientSet',
strict: true,
})
if (!log) throw new Error('`RewardRecipientSet` event not found.')
return log
}
}
export declare namespace setRecipientSync {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = WriteParameters<chain, account> & setRecipient.Args
export type ReturnValue = {
/** The token holder address who set their reward recipient */
holder: Address
/** The transaction receipt */
receipt: Awaited<ReturnType<typeof writeContractSync>>
/** The reward recipient address (zero address indicates opt-out) */
recipient: Address
}
export type ErrorType = setRecipient.ErrorType
}
/**
* Watches for reward distributed events.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const unwatch = Actions.reward.watchRewardDistributed(client, {
* token: '0x20c0000000000000000000000000000000000001',
* onRewardDistributed: (args, log) => {
* console.log('Reward distributed:', args)
* },
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns A function to unsubscribe from the event.
*/
export function watchRewardDistributed<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: watchRewardDistributed.Parameters,
) {
const { onRewardDistributed, token, ...rest } = parameters
return watchContractEvent(client, {
...rest,
address: token,
abi: Abis.tip20,
eventName: 'RewardDistributed',
onLogs: (logs) => {
for (const log of logs) onRewardDistributed(log.args, log)
},
strict: true,
})
}
export declare namespace watchRewardDistributed {
export type Args = GetEventArgs<
typeof Abis.tip20,
'RewardDistributed',
{ IndexedOnly: false; Required: true }
>
export type Log = viem_Log<
bigint,
number,
false,
ExtractAbiItem<typeof Abis.tip20, 'RewardDistributed'>,
true
>
export type Parameters = UnionOmit<
WatchContractEventParameters<typeof Abis.tip20, 'RewardDistributed', true>,
'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'
> & {
/** Callback to invoke when rewards are distributed. */
onRewardDistributed: (args: Args, log: Log) => void
/** The TIP20 token address */
token: Address
}
export type ReturnValue = WatchContractEventReturnType
}
/**
* Watches for reward recipient set events.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const unwatch = Actions.reward.watchRewardRecipientSet(client, {
* token: '0x20c0000000000000000000000000000000000001',
* onRewardRecipientSet: (args, log) => {
* console.log('Reward recipient set:', args)
* },
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns A function to unsubscribe from the event.
*/
export function watchRewardRecipientSet<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: watchRewardRecipientSet.Parameters,
) {
const { onRewardRecipientSet, token, ...rest } = parameters
return watchContractEvent(client, {
...rest,
address: token,
abi: Abis.tip20,
eventName: 'RewardRecipientSet',
onLogs: (logs) => {
for (const log of logs) onRewardRecipientSet(log.args, log)
},
strict: true,
})
}
export declare namespace watchRewardRecipientSet {
export type Args = GetEventArgs<
typeof Abis.tip20,
'RewardRecipientSet',
{ IndexedOnly: false; Required: true }
>
export type Log = viem_Log<
bigint,
number,
false,
ExtractAbiItem<typeof Abis.tip20, 'RewardRecipientSet'>,
true
>
export type Parameters = UnionOmit<
WatchContractEventParameters<typeof Abis.tip20, 'RewardRecipientSet', true>,
'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'
> & {
/** Callback to invoke when a reward recipient is set. */
onRewardRecipientSet: (args: Args, log: Log) => void
/** The TIP20 token address */
token: Address
}
export type ReturnValue = WatchContractEventReturnType
}

452
node_modules/viem/tempo/actions/simulate.ts generated vendored Normal file
View File

@@ -0,0 +1,452 @@
import type { Abi, AbiStateMutability, Address, Narrow } from 'abitype'
import * as BlockOverrides from 'ox/BlockOverrides'
import type * as RpcSchema from 'ox/RpcSchema'
import type { RpcSchemaTempo } from 'ox/tempo'
import {
type ParseAccountErrorType,
parseAccount,
} from '../../accounts/utils/parseAccount.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { AbiDecodingZeroDataError } from '../../errors/abi.js'
import type { BaseError } from '../../errors/base.js'
import { RawContractError } from '../../errors/contract.js'
import { UnknownNodeError } from '../../errors/node.js'
import type { ErrorType as ErrorType_ } from '../../errors/utils.js'
import type { Account } from '../../types/account.js'
import type { Block, BlockTag } from '../../types/block.js'
import type { Call, Calls } from '../../types/calls.js'
import type { Chain } from '../../types/chain.js'
import type { Log } from '../../types/log.js'
import type { Hex } from '../../types/misc.js'
import type { MulticallResults } from '../../types/multicall.js'
import type { StateOverride } from '../../types/stateOverride.js'
import type { TransactionRequest } from '../../types/transaction.js'
import type { ExactPartial, UnionOmit } from '../../types/utils.js'
import {
type DecodeFunctionResultErrorType,
decodeFunctionResult,
} from '../../utils/abi/decodeFunctionResult.js'
import {
type EncodeFunctionDataErrorType,
encodeFunctionData,
} from '../../utils/abi/encodeFunctionData.js'
import { concat } from '../../utils/data/concat.js'
import {
type NumberToHexErrorType,
numberToHex,
} from '../../utils/encoding/toHex.js'
import { getContractError } from '../../utils/errors/getContractError.js'
import {
type GetNodeErrorReturnType,
getNodeError,
} from '../../utils/errors/getNodeError.js'
import {
type FormatBlockErrorType,
formatBlock,
} from '../../utils/formatters/block.js'
import { formatLog } from '../../utils/formatters/log.js'
import {
type FormatTransactionRequestErrorType,
formatTransactionRequest,
} from '../../utils/formatters/transactionRequest.js'
import {
type SerializeStateOverrideErrorType,
serializeStateOverride,
} from '../../utils/stateOverride.js'
import {
type AssertRequestErrorType,
assertRequest,
} from '../../utils/transaction/assertRequest.js'
export type TokenMetadata = {
[address: Hex]: {
name: string
symbol: string
currency: string
}
}
type CallExtraProperties = ExactPartial<
UnionOmit<
TransactionRequest,
'blobs' | 'data' | 'kzg' | 'to' | 'sidecars' | 'value'
>
> & {
/** Account attached to the call (msg.sender). */
account?: Account | Address | undefined
/** Recipient. `null` if contract deployment. */
to?: Address | null | undefined
}
/**
* Simulates a set of calls on block(s) via `tempo_simulateV1`.
*
* Returns simulated block results and token metadata for any TIP-20
* tokens involved in the simulation.
*
* @example
* ```ts
* import { createClient, http, parseUnits } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* account: '0x...',
* chain: tempo,
* transport: http(),
* })
*
* const { blocks, tokenMetadata } = await Actions.simulate.simulateBlocks(client, {
* blocks: [{
* calls: [
* Actions.token.transfer.call({
* token: '0x20c0...01',
* to: '0x...',
* amount: parseUnits('100', 6),
* }),
* ],
* }],
* traceTransfers: true,
* })
* ```
*
* @param client - Client.
* @param parameters - {@link simulateBlocks.Parameters}
* @returns Simulated blocks and token metadata. {@link simulateBlocks.ReturnType}
*/
export async function simulateBlocks<
chain extends Chain | undefined,
const calls extends readonly unknown[],
>(
client: Client<Transport, chain>,
parameters: simulateBlocks.Parameters<calls>,
): Promise<simulateBlocks.ReturnType<calls>> {
const {
blockNumber,
blockTag = client.experimental_blockTag ?? 'latest',
blocks,
returnFullTransactions,
traceTransfers,
validation,
} = parameters
try {
const blockStateCalls = []
for (const block of blocks) {
const blockOverrides = block.blockOverrides
? BlockOverrides.toRpc(block.blockOverrides)
: undefined
const calls = block.calls.map((call_) => {
const call = call_ as Call<unknown, CallExtraProperties>
const account = call.account
? parseAccount(call.account)
: client.account
? parseAccount(client.account)
: undefined
const data = call.abi ? encodeFunctionData(call) : call.data
const request = {
...call,
account,
data: call.dataSuffix
? concat([data || '0x', call.dataSuffix])
: data,
from: call.from ?? account?.address,
} as const
assertRequest(request)
return formatTransactionRequest(request)
})
const stateOverrides = block.stateOverrides
? serializeStateOverride(block.stateOverrides)
: undefined
blockStateCalls.push({
blockOverrides,
calls,
stateOverrides,
})
}
const blockNumberHex =
typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined
const block = blockNumberHex || blockTag
type tempo_simulateV1 = RpcSchema.ToViem<RpcSchemaTempo.Tempo>[0]
const result = await client.request<tempo_simulateV1>({
method: 'tempo_simulateV1',
params: [
{
blockStateCalls,
returnFullTransactions,
traceTransfers,
validation,
} as tempo_simulateV1['Parameters'][0],
block,
],
})
return {
blocks: result.blocks.map((block, i) => ({
...formatBlock(block as never),
calls: block.calls?.map((call, j) => {
const { abi, args, functionName, to } = blocks[i].calls[j] as Call<
unknown,
CallExtraProperties
>
const data = call.error?.data ?? call.returnData
const gasUsed = BigInt(call.gasUsed)
const logs = call.logs?.map((log) => formatLog(log))
const status = call.status === '0x1' ? 'success' : 'failure'
const result =
abi && status === 'success' && data !== '0x'
? decodeFunctionResult({
abi,
data,
functionName,
})
: null
const error = (() => {
if (status === 'success') return undefined
let error: Error | undefined
if (data === '0x') error = new AbiDecodingZeroDataError()
else if (data) error = new RawContractError({ data })
if (!error) return undefined
return getContractError(error, {
abi: (abi ?? []) as Abi,
address: to ?? '0x',
args,
functionName: functionName ?? '<unknown>',
})
})()
return {
data,
gasUsed,
logs,
status,
...(status === 'success'
? {
result,
}
: {
error,
}),
}
}),
})),
tokenMetadata: result.tokenMetadata ?? {},
} as unknown as simulateBlocks.ReturnType<calls>
} catch (e) {
const cause = e as BaseError
const error = getNodeError(cause, {})
if (error instanceof UnknownNodeError) throw cause
throw error
}
}
export declare namespace simulateBlocks {
export type Parameters<
calls extends readonly unknown[] = readonly unknown[],
> = {
/** Blocks to simulate. */
blocks: readonly {
/** Block overrides. */
blockOverrides?: BlockOverrides.BlockOverrides | undefined
/** Calls to execute. */
calls: Calls<Narrow<calls>, CallExtraProperties>
/** State overrides. */
stateOverrides?: StateOverride | undefined
}[]
/** Whether to return the full transactions. */
returnFullTransactions?: boolean | undefined
/** Whether to trace transfers. */
traceTransfers?: boolean | undefined
/** Whether to enable validation mode. */
validation?: boolean | 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.
* @default 'latest'
*/
blockTag?: BlockTag | undefined
}
)
export type ReturnType<
calls extends readonly unknown[] = readonly unknown[],
> = {
blocks: readonly (Block & {
calls: MulticallResults<
Narrow<calls>,
true,
{
extraProperties: {
data: Hex
gasUsed: bigint
logs?: Log[] | undefined
}
error: Error
mutability: AbiStateMutability
}
>
})[]
tokenMetadata: TokenMetadata
}
export type ErrorType =
| AssertRequestErrorType
| DecodeFunctionResultErrorType
| EncodeFunctionDataErrorType
| FormatBlockErrorType
| FormatTransactionRequestErrorType
| GetNodeErrorReturnType
| ParseAccountErrorType
| SerializeStateOverrideErrorType
| NumberToHexErrorType
| ErrorType_
}
/**
* Simulates execution of a batch of calls via `tempo_simulateV1`.
*
* A convenience wrapper around {@link simulateBlocks} that runs all
* calls in a single block and returns flattened results.
*
* @example
* ```ts
* import { createClient, http, parseUnits } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions, Addresses } from 'viem/tempo'
*
* const client = createClient({
* account: '0x...',
* chain: tempo,
* transport: http(),
* })
*
* const { results, tokenMetadata } = await Actions.simulate.simulateCalls(client, {
* calls: [
* Actions.token.approve.call({
* token: '0x20c0...01',
* spender: Addresses.stablecoinDex,
* amount: parseUnits('100', 6),
* }),
* Actions.dex.buy.call({
* tokenIn: '0x20c0...01',
* tokenOut: '0x20c0...02',
* amountOut: parseUnits('10', 6),
* maxAmountIn: parseUnits('100', 6),
* }),
* Actions.token.transfer.call({
* token: '0x20c0...02',
* to: '0x...',
* amount: parseUnits('10', 6),
* }),
* ],
* })
* ```
*
* @param client - Client.
* @param parameters - {@link simulateCalls.Parameters}
* @returns Results, block, and token metadata. {@link simulateCalls.ReturnType}
*/
export async function simulateCalls<
const calls extends readonly unknown[],
chain extends Chain | undefined,
account extends Account | Address | undefined = undefined,
>(
client: Client<Transport, chain>,
parameters: simulateCalls.Parameters<calls, account>,
): Promise<simulateCalls.ReturnType<calls>> {
const {
blockNumber,
blockTag,
calls,
stateOverrides,
traceTransfers,
validation,
} = parameters
const account = parameters.account
? parseAccount(parameters.account)
: undefined
const result = await simulateBlocks(client, {
blockNumber,
blockTag: blockTag as undefined,
blocks: [
{
calls: calls.map((call) => ({
...(call as Call),
from: account?.address,
})) as any,
stateOverrides,
},
],
traceTransfers,
validation,
})
const { calls: block_calls, ...block } = result.blocks[0]
return {
block,
results: block_calls,
tokenMetadata: result.tokenMetadata,
} as unknown as simulateCalls.ReturnType<calls>
}
export declare namespace simulateCalls {
export type Parameters<
calls extends readonly unknown[] = readonly unknown[],
account extends Account | Address | undefined =
| Account
| Address
| undefined,
> = Omit<simulateBlocks.Parameters, 'blocks' | 'returnFullTransactions'> & {
/** Account attached to the calls (msg.sender). */
account?: account | undefined
/** Calls to simulate. */
calls: Calls<Narrow<calls>>
/** State overrides. */
stateOverrides?: StateOverride | undefined
}
export type ReturnType<
calls extends readonly unknown[] = readonly unknown[],
> = {
/** Block results. */
block: Block
/** Call results. */
results: MulticallResults<
Narrow<calls>,
true,
{
extraProperties: {
data: Hex
gasUsed: bigint
logs?: Log[] | undefined
}
error: Error
mutability: AbiStateMutability
}
>
/** Token metadata resolved from the simulation. */
tokenMetadata: TokenMetadata
}
export type ErrorType = simulateBlocks.ErrorType | ErrorType_
}

4471
node_modules/viem/tempo/actions/token.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

1417
node_modules/viem/tempo/actions/validator.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

337
node_modules/viem/tempo/actions/virtualAddress.ts generated vendored Normal file
View File

@@ -0,0 +1,337 @@
import type { Address } from 'abitype'
import * as Hex from 'ox/Hex'
import type { Account } from '../../accounts/types.js'
import { readContract } from '../../actions/public/readContract.js'
import type { WriteContractReturnType } from '../../actions/wallet/writeContract.js'
import { writeContract } from '../../actions/wallet/writeContract.js'
import { writeContractSync } from '../../actions/wallet/writeContractSync.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { zeroAddress } from '../../constants/address.js'
import type { BaseErrorType } from '../../errors/base.js'
import type { Chain } from '../../types/chain.js'
import type { GetEventArgs } from '../../types/contract.js'
import type { Compute } from '../../types/utils.js'
import { parseEventLogs } from '../../utils/abi/parseEventLogs.js'
import * as Abis from '../Abis.js'
import * as Addresses from '../Addresses.js'
import type { ReadParameters, WriteParameters } from '../internal/types.js'
import { defineCall } from '../internal/utils.js'
import type { TransactionReceipt } from '../Transaction.js'
/**
* Gets the master address for a given master ID.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const address = await Actions.virtualAddress.getMasterAddress(client, {
* masterId: '0xdeadbeef',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The master address, or null if unregistered.
*/
export async function getMasterAddress<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: getMasterAddress.Parameters,
): Promise<getMasterAddress.ReturnValue> {
const address = await readContract(client, {
...parameters,
...getMasterAddress.call({ masterId: parameters.masterId }),
})
if (address === zeroAddress) return null
return address
}
export namespace getMasterAddress {
export type Parameters = ReadParameters & Args
export type Args = {
/** The master ID (bytes4). */
masterId: Hex.Hex
}
export type ReturnValue = Address | null
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
/**
* Defines a call to the `getMaster` function.
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { masterId } = args
return defineCall({
address: Addresses.addressRegistry,
abi: Abis.addressRegistry,
args: [masterId],
functionName: 'getMaster',
})
}
}
/**
* Resolves a virtual address to its master address.
*
* - Non-virtual addresses are returned unchanged.
* - Virtual addresses with a registered master return the master address.
* - Virtual addresses with an unregistered master return null.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const recipient = await Actions.virtualAddress.resolve(client, {
* address: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The resolved address, or null if virtual and unregistered.
*/
export async function resolve<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: resolve.Parameters,
): Promise<resolve.ReturnValue> {
if (!isVirtual(parameters.address)) return parameters.address
const masterId = Hex.slice(parameters.address, 0, 4)
return getMasterAddress(client, { ...parameters, masterId })
}
export namespace resolve {
export type Parameters = ReadParameters & Args
export type Args = {
/** The address to resolve. */
address: Address
}
export type ReturnValue = Address | null
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
}
/**
* Registers a virtual master address.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const hash = await Actions.virtualAddress.registerMaster(client, {
* salt: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function registerMaster<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: registerMaster.Parameters<chain, account>,
): Promise<registerMaster.ReturnValue> {
return registerMaster.inner(writeContract, client, parameters)
}
export namespace registerMaster {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = WriteParameters<chain, account> & Args
export type Args = {
/** The salt (bytes32) used for proof-of-work master ID derivation. */
salt: Hex.Hex
}
export type ReturnValue = WriteContractReturnType
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
/** @internal */
export async function inner<
action extends typeof writeContract | typeof writeContractSync,
chain extends Chain | undefined,
account extends Account | undefined,
>(
action: action,
client: Client<Transport, chain, account>,
parameters: registerMaster.Parameters<chain, account>,
): Promise<ReturnType<action>> {
const { salt, ...rest } = parameters
const call = registerMaster.call({ salt })
return (await action(client, {
...rest,
...call,
} as never)) as never
}
/**
* Defines a call to the `registerVirtualMaster` function.
*
* Can be passed as a parameter to:
* - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call
* - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call
* - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls
*
* @example
* ```ts
* import { createClient, http, walletActions } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
*
* const client = createClient({
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* }).extend(walletActions)
*
* const { result } = await client.sendCalls({
* calls: [
* Actions.virtualAddress.registerMaster.call({
* salt: '0x...',
* }),
* ]
* })
* ```
*
* @param args - Arguments.
* @returns The call.
*/
export function call(args: Args) {
const { salt } = args
return defineCall({
address: Addresses.addressRegistry,
abi: Abis.addressRegistry,
functionName: 'registerVirtualMaster',
args: [salt],
})
}
export function extractEvent(logs: import('../../types/log.js').Log[]) {
const [log] = parseEventLogs({
abi: Abis.addressRegistry,
logs,
eventName: 'MasterRegistered',
strict: true,
})
if (!log) throw new Error('`MasterRegistered` event not found.')
return log
}
}
/**
* Registers a virtual master address and waits for confirmation.
*
* @example
* ```ts
* import { createClient, http } from 'viem'
* import { tempo } from 'viem/chains'
* import { Actions } from 'viem/tempo'
* import { privateKeyToAccount } from 'viem/accounts'
*
* const client = createClient({
* account: privateKeyToAccount('0x...'),
* chain: tempo.extend({ feeToken: '0x20c0000000000000000000000000000000000001' })
* transport: http(),
* })
*
* const { receipt, masterId, masterAddress } = await Actions.virtualAddress.registerMasterSync(client, {
* salt: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and extracted event data.
*/
export async function registerMasterSync<
chain extends Chain | undefined,
account extends Account | undefined,
>(
client: Client<Transport, chain, account>,
parameters: registerMasterSync.Parameters<chain, account>,
): Promise<registerMasterSync.ReturnValue> {
const { throwOnReceiptRevert = true, ...rest } = parameters
const receipt = await registerMaster.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
} as never)
const { args } = registerMaster.extractEvent(receipt.logs)
return {
...args,
receipt,
} as never
}
export namespace registerMasterSync {
export type Parameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = registerMaster.Parameters<chain, account>
export type Args = registerMaster.Args
export type ReturnValue = Compute<
GetEventArgs<
typeof Abis.addressRegistry,
'MasterRegistered',
{ IndexedOnly: false; Required: true }
> & {
receipt: TransactionReceipt
}
>
// TODO: exhaustive error type
export type ErrorType = BaseErrorType
}
const virtualMagic = '0xfdfdfdfdfdfdfdfdfdfd'
/** @internal */
function isVirtual(address: string): boolean {
return Hex.slice(address as Hex.Hex, 4, 14).toLowerCase() === virtualMagic
}

1317
node_modules/viem/tempo/actions/zone.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

175
node_modules/viem/tempo/chainConfig.ts generated vendored Normal file
View File

@@ -0,0 +1,175 @@
import * as Address from 'ox/Address'
import * as Hex from 'ox/Hex'
import * as PublicKey from 'ox/PublicKey'
import { SignatureEnvelope, type TokenId } from 'ox/tempo'
import { getCode } from '../actions/public/getCode.js'
import { verifyHash } from '../actions/public/verifyHash.js'
import { maxUint256 } from '../constants/number.js'
import type { Chain, ChainConfig as viem_ChainConfig } from '../types/chain.js'
import { extendSchema } from '../utils/chain/defineChain.js'
import { defineTransaction } from '../utils/formatters/transaction.js'
import { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js'
import { defineTransactionRequest } from '../utils/formatters/transactionRequest.js'
import { getAction } from '../utils/getAction.js'
import { keccak256 } from '../utils/hash/keccak256.js'
import type { SerializeTransactionFn } from '../utils/transaction/serializeTransaction.js'
import type { Account } from './Account.js'
import { getMetadata } from './actions/accessKey.js'
import * as Formatters from './Formatters.js'
import type { Hardfork } from './Hardfork.js'
import * as Concurrent from './internal/concurrent.js'
import * as Transaction from './Transaction.js'
const maxExpirySecs = 25
export const chainConfig = {
blockTime: 1_000,
extendSchema: extendSchema<{
feeToken?: TokenId.TokenIdOrAddress | undefined
hardfork?: Hardfork | undefined
}>(),
formatters: {
transaction: defineTransaction({
exclude: ['aaAuthorizationList' as never],
format: Formatters.formatTransaction,
}),
transactionReceipt: defineTransactionReceipt({
format: Formatters.formatTransactionReceipt,
}),
transactionRequest: defineTransactionRequest({
format: Formatters.formatTransactionRequest,
}),
},
prepareTransactionRequest: [
async (r, { phase }) => {
const request = r as Transaction.TransactionRequest & {
account?: Account | undefined
chain?:
| (Chain & { feeToken?: TokenId.TokenIdOrAddress | undefined })
| undefined
}
// FIXME: node estimates gas with secp256k1 dummy sig + null feePayerSignature.
// Actual tx has larger keychain/webAuthn sigs + real fee payer sig, costing more intrinsic gas.
if (phase === 'afterFillParameters') {
if (request.feePayer) {
if (request.keyAuthorization?.signature.type === 'webAuthn')
request.gas = (request.gas ?? 0n) + 20_000n
else if (request.account?.source === 'accessKey')
request.gas = (request.gas ?? 0n) + 10_000n
}
return request as unknown as typeof r
}
// Use expiring nonces for concurrent transactions (TIP-1009).
// When nonceKey is 'expiring', feePayer is specified, or concurrent requests
// are detected, we use expiring nonces (nonceKey = uint256.max) with a
// validBefore timestamp.
const useExpiringNonce = await (async () => {
if (request.nonceKey === 'expiring') return true
if (request.feePayer && typeof request.nonceKey === 'undefined')
return true
const address = request.account?.address
if (address && typeof request.nonceKey === 'undefined')
return await Concurrent.detect(address)
return false
})()
if (useExpiringNonce) {
request.nonceKey = maxUint256
request.nonce = 0
if (typeof request.validBefore === 'undefined')
request.validBefore = Math.floor(Date.now() / 1000) + maxExpirySecs
} else if (typeof request.nonceKey !== 'undefined') {
// Explicit nonceKey provided (2D nonce mode)
request.nonce = typeof request.nonce === 'number' ? request.nonce : 0
}
if (!request.feeToken && request.chain?.feeToken)
request.feeToken = request.chain.feeToken
return request as unknown as typeof r
},
{ runAt: ['beforeFillTransaction', 'afterFillParameters'] },
],
serializers: {
// TODO: casting to satisfy viem viem v3 to have more flexible serializer type.
transaction: ((transaction, signature) =>
Transaction.serialize(transaction, signature)) as SerializeTransactionFn,
},
async verifyHash(client, parameters) {
const { address, hash, signature, mode } = parameters
const envelope = (() => {
if (typeof signature !== 'string') return
try {
return SignatureEnvelope.deserialize(signature)
} catch {
return undefined
}
})()
// `verifyHash` supports "signature envelopes" (a Tempo proposal) to natively verify arbitrary
// envelope-compatible (WebAuthn, P256, etc.) signatures.
if (envelope) {
// Access key (keychain) signature verification: check the key is
// authorized, not expired, and not revoked on the AccountKeychain.
if (envelope?.type === 'keychain' && mode === 'allowAccessKey') {
const accessKeyAddress = Address.fromPublicKey(
PublicKey.from(envelope.inner.publicKey as PublicKey.PublicKey),
)
const keyInfo = await getMetadata(client, {
account: address,
accessKey: accessKeyAddress,
blockNumber: parameters.blockNumber,
blockTag: parameters.blockTag,
} as never)
if (keyInfo.isRevoked) return false
if (keyInfo.expiry <= BigInt(Math.floor(Date.now() / 1000)))
return false
// For v2 keychain envelopes, the inner signature signs
// keccak256(0x04 || hash || userAddress).
const innerPayload =
envelope.version === 'v2'
? keccak256(Hex.concat('0x04', hash, address))
: hash
return SignatureEnvelope.verify(envelope.inner, {
address: accessKeyAddress,
payload: innerPayload,
})
}
// Stateless, non-keychain signature envelopes (P256, WebAuthn) can be
// verified directly without a network request.
if (envelope.type === 'p256' || envelope.type === 'webAuthn') {
const code = await getCode(client, {
address,
blockNumber: parameters.blockNumber,
blockTag: parameters.blockTag,
} as never)
// Check if EOA, if not, we want to go down the ERC-1271 flow.
if (
// not a contract (EOA)
!code ||
// default delegation (tempo EOA)
code === '0xef01007702c00000000000000000000000000000000000'
)
return SignatureEnvelope.verify(envelope, {
address,
payload: hash,
})
}
}
return await getAction(
client,
verifyHash,
'verifyHash',
)({ ...parameters, chain: null })
},
} as const satisfies viem_ChainConfig & { blockTime: number }
export type ChainConfig = typeof chainConfig

70
node_modules/viem/tempo/index.ts generated vendored Normal file
View File

@@ -0,0 +1,70 @@
// biome-ignore lint/performance/noBarrelFile: entrypoint module
export { Bytes, PublicKey, Secp256k1 } from 'ox'
// Export types required for inference.
export type {
/** @deprecated */
KeyAuthorization as z_KeyAuthorization,
/** @deprecated */
SignatureEnvelope as z_SignatureEnvelope,
/** @deprecated */
TokenId as z_TokenId,
/** @deprecated */
TxEnvelopeTempo as z_TxEnvelopeTempo,
} from 'ox/tempo'
export {
Period,
TempoAddress,
Tick,
TokenId,
VirtualAddress,
VirtualMaster,
} from 'ox/tempo'
export * as Abis from './Abis.js'
export * as Account from './Account.js'
export * as Addresses from './Addresses.js'
export * as Actions from './actions/index.js'
export * as Capabilities from './Capabilities.js'
export {
type Decorator as TempoActions,
decorator as tempoActions,
} from './Decorator.js'
export * as Expiry from './Expiry.js'
export * as Formatters from './Formatters.js'
export * as Hardfork from './Hardfork.js'
export * as P256 from './P256.js'
export * as Storage from './Storage.js'
export * as TokenIds from './TokenIds.js'
// Export types required for inference.
export type {
/** @deprecated */
Transaction as z_Transaction,
/** @deprecated */
TransactionReceipt as z_TransactionReceipt,
/** @deprecated */
TransactionReceiptRpc as z_TransactionReceiptRpc,
/** @deprecated */
TransactionRequest as z_TransactionRequest,
/** @deprecated */
TransactionRequestRpc as z_TransactionRequestRpc,
/** @deprecated */
TransactionRequestTempo as z_TransactionRequestTempo,
/** @deprecated */
TransactionRpc as z_TransactionRpc,
/** @deprecated */
TransactionSerializable as z_TransactionSerializable,
/** @deprecated */
TransactionSerializableTempo as z_TransactionSerializableTempo,
/** @deprecated */
TransactionSerialized as z_TransactionSerialized,
/** @deprecated */
TransactionSerializedTempo as z_TransactionSerializedTempo,
/** @deprecated */
TransactionTempo as z_TransactionTempo,
/** @deprecated */
TransactionType as z_TransactionType,
} from './Transaction.js'
export * as Transaction from './Transaction.js'
export * as Transport from './Transport.js'
export { walletNamespaceCompat, withFeePayer, withRelay } from './Transport.js'
export * as WebAuthnP256 from './WebAuthnP256.js'
export * as WebCryptoP256 from './WebCryptoP256.js'

24
node_modules/viem/tempo/internal/concurrent.ts generated vendored Normal file
View File

@@ -0,0 +1,24 @@
const concurrentCounts = new Map<string, number>()
/**
* Detects if there are concurrent tasks occuring for a given key
* within the same event loop tick. Registers the request, yields to allow
* other concurrent calls to register, then returns whether multiple requests
* were detected.
*
* @example
* ```ts
* const isConcurrent = await Concurrent.detect(address)
* ```
*/
export async function detect(key: string): Promise<boolean> {
concurrentCounts.set(key, (concurrentCounts.get(key) ?? 0) + 1)
await Promise.resolve()
const isConcurrent = (concurrentCounts.get(key) ?? 0) > 1
queueMicrotask(() => {
const count = concurrentCounts.get(key) ?? 0
if (count <= 1) concurrentCounts.delete(key)
else concurrentCounts.set(key, count - 1)
})
return isConcurrent
}

60
node_modules/viem/tempo/internal/types.ts generated vendored Normal file
View File

@@ -0,0 +1,60 @@
import type { Address } from 'abitype'
import type { Account } from '../../accounts/types.js'
import type { ReadContractParameters as viem_ReadContractParameters } from '../../actions/public/readContract.js'
import type { WriteContractSyncParameters as viem_WriteContractSyncParameters } from '../../actions/wallet/writeContractSync.js'
import type { Chain } from '../../types/chain.js'
import type {
IsUndefined,
MaybeRequired,
UnionPick,
} from '../../types/utils.js'
import type { TransactionRequestTempo } from '../Transaction.js'
export type GetAccountParameter<
account extends Account | undefined = Account | undefined,
accountOverride extends Account | Address | undefined = Account | Address,
required extends boolean = true,
nullish extends boolean = false,
> = MaybeRequired<
{
account?:
| accountOverride
| Account
| Address
| (nullish extends true ? null : never)
| undefined
},
IsUndefined<account> extends true
? required extends true
? true
: false
: false
>
export type ReadParameters = Pick<
viem_ReadContractParameters<never, never, never>,
'account' | 'blockNumber' | 'blockOverrides' | 'blockTag' | 'stateOverride'
>
export type WriteParameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
> = UnionPick<
viem_WriteContractSyncParameters<never, never, never, chain, account>,
| 'account'
| 'chain'
| 'gas'
| 'maxFeePerGas'
| 'maxPriorityFeePerGas'
| 'nonce'
| 'throwOnReceiptRevert'
> &
UnionPick<
TransactionRequestTempo,
| 'keyAuthorization'
| 'feeToken'
| 'feePayer'
| 'nonceKey'
| 'validAfter'
| 'validBefore'
>

57
node_modules/viem/tempo/internal/utils.ts generated vendored Normal file
View File

@@ -0,0 +1,57 @@
import type { Abi, AbiStateMutability, Address } from 'abitype'
import type {
ContractFunctionName,
ContractFunctionParameters,
ExtractAbiItem,
} from '../../types/contract.js'
import type { Hex } from '../../types/misc.js'
import { encodeFunctionData } from '../../utils/index.js'
export function defineCall<
const abi extends Abi,
const functionName extends ContractFunctionName<abi, AbiStateMutability>,
call extends ContractFunctionParameters<
abi,
AbiStateMutability,
functionName
>,
>(
call:
| call
| ContractFunctionParameters<abi, AbiStateMutability, functionName>,
): ContractFunctionParameters<
[ExtractAbiItem<abi, functionName>],
AbiStateMutability,
functionName
> & {
data: Hex
to: Address
} {
return {
...(call as any),
data: encodeFunctionData(call as never),
to: call.address,
} as const
}
/**
* Normalizes a value into a structured-clone compatible format.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone
* @internal
*/
export function normalizeValue<type>(value: type): type {
if (Array.isArray(value)) return value.map(normalizeValue) as never
if (typeof value === 'function') return undefined as never
if (typeof value !== 'object' || value === null) return value
if (Object.getPrototypeOf(value) !== Object.prototype)
try {
return structuredClone(value)
} catch {
return undefined as never
}
const normalized: Record<string, unknown> = {}
for (const [k, v] of Object.entries(value)) normalized[k] = normalizeValue(v)
return normalized as never
}

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

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

79
node_modules/viem/tempo/zones/Abis.ts generated vendored Normal file
View File

@@ -0,0 +1,79 @@
export const zonePortal = [
{
name: 'deposit',
type: 'function',
stateMutability: 'nonpayable',
inputs: [
{ name: '_token', type: 'address' },
{ name: 'to', type: 'address' },
{ name: 'amount', type: 'uint128' },
{ name: 'memo', type: 'bytes32' },
],
outputs: [{ name: '', type: 'bytes32' }],
},
{
name: 'depositEncrypted',
type: 'function',
stateMutability: 'nonpayable',
inputs: [
{ name: 'token', type: 'address' },
{ name: 'amount', type: 'uint128' },
{ name: 'keyIndex', type: 'uint256' },
{
name: 'encrypted',
type: 'tuple',
components: [
{ name: 'ephemeralPubkeyX', type: 'bytes32' },
{ name: 'ephemeralPubkeyYParity', type: 'uint8' },
{ name: 'ciphertext', type: 'bytes' },
{ name: 'nonce', type: 'bytes12' },
{ name: 'tag', type: 'bytes16' },
],
},
],
outputs: [{ name: '', type: 'bytes32' }],
},
{
name: 'sequencerEncryptionKey',
type: 'function',
stateMutability: 'view',
inputs: [],
outputs: [
{ name: 'x', type: 'bytes32' },
{ name: 'yParity', type: 'uint8' },
],
},
{
name: 'encryptionKeyCount',
type: 'function',
stateMutability: 'view',
inputs: [],
outputs: [{ name: '', type: 'uint256' }],
},
] as const
export const zoneOutbox = [
{
name: 'requestWithdrawal',
type: 'function',
stateMutability: 'nonpayable',
inputs: [
{ name: 'token', type: 'address' },
{ name: 'to', type: 'address' },
{ name: 'amount', type: 'uint128' },
{ name: 'memo', type: 'bytes32' },
{ name: 'gasLimit', type: 'uint64' },
{ name: 'fallbackRecipient', type: 'address' },
{ name: 'data', type: 'bytes' },
{ name: 'revealTo', type: 'bytes' },
],
outputs: [],
},
{
name: 'calculateWithdrawalFee',
type: 'function',
stateMutability: 'view',
inputs: [{ name: 'gasLimit', type: 'uint64' }],
outputs: [{ name: 'fee', type: 'uint128' }],
},
] as const

10
node_modules/viem/tempo/zones/index.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
// biome-ignore lint/performance/noBarrelFile: entrypoint module
export * as Abis from './Abis.js'
export { http, type ZoneHttpConfig } from './transport.js'
export {
from,
getPortalAddress,
portalAddresses,
zone,
zoneModerato,
} from './zone.js'

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

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

58
node_modules/viem/tempo/zones/transport.ts generated vendored Normal file
View File

@@ -0,0 +1,58 @@
import {
type HttpTransport,
type HttpTransportConfig,
http as http_,
} from '../../clients/transports/http.js'
import type { Storage } from '../Storage.js'
import * as Storage_ from '../Storage.js'
export type ZoneHttpConfig = Omit<
HttpTransportConfig,
'batch' | 'raw' | 'rpcSchema'
> & {
/** Storage for reading zone authorization tokens. Defaults to sessionStorage (web) or memory (server). */
storage?: Storage | undefined
}
/**
* Creates an HTTP transport with support for Zone authentication tokens.
*
* Reads the authorization token from Storage and injects the
* `X-Authorization-Token` header on every request. Batching is disabled
* by default because zone tokens are account-scoped.
*
* @example
* ```ts
* import { createPublicClient } from 'viem'
* import { http, zone } from 'viem/tempo/zones' // or zoneModerato
*
* const client = createPublicClient({
* chain: zone(6),
* transport: http(),
* })
* ```
*/
export function http(
url?: string | undefined,
config: ZoneHttpConfig = {},
): HttpTransport {
const { storage: storage_, onFetchRequest, ...rest } = config
const storage = storage_ ?? Storage_.defaultStorage()
return (config) =>
http_(url, {
...rest,
async onFetchRequest(request, init) {
const next = (await onFetchRequest?.(request, init)) ?? init
const headers = new Headers(next.headers)
const chainId = config.chain?.id
if (chainId) {
const token = (await storage.getItem(`auth:token:${chainId}`)) ?? null
if (token) headers.set('X-Authorization-Token', token)
}
return { ...next, headers }
},
})(config)
}

70
node_modules/viem/tempo/zones/zone.ts generated vendored Normal file
View File

@@ -0,0 +1,70 @@
import { ZoneId } from 'ox/tempo'
import { tempo } from '../../chains/definitions/tempo.js'
import { tempoModerato } from '../../chains/definitions/tempoModerato.js'
import { defineChain } from '../../utils/chain/defineChain.js'
import { chainConfig } from '../chainConfig.js'
export const portalAddresses = {
[tempoModerato.id]: {
6: '0x7069DeC4E64Fd07334A0933eDe836C17259c9B23',
7: '0x3F5296303400B56271b476F5A0B9cBF74350D6Ac',
},
} as const satisfies Record<number, Record<number, `0x${string}`>>
export function getPortalAddress(
chainId: number,
zoneId: number,
): `0x${string}` {
const address = (
portalAddresses as Record<number, Record<number, `0x${string}`>>
)[chainId]?.[zoneId]
if (!address)
throw new Error(
`No portal address configured for zone ${zoneId} on chain ${chainId}.`,
)
return address
}
export const zone = /*#__PURE__*/ from({
sourceId: tempo.id,
rpcHost: 'tempo.xyz',
})
export const zoneModerato = /*#__PURE__*/ from({
sourceId: tempoModerato.id,
rpcHost: 'tempoxyz.dev',
})
/** Creates a zone chain factory for a given Tempo network. */
export function from(options: from.Options) {
return (id: number) => {
const chainId = ZoneId.toChainId(id)
const paddedId = String(id).padStart(3, '0')
return defineChain({
...chainConfig,
id: chainId,
name: `Tempo Zone ${paddedId}`,
nativeCurrency: {
name: 'USD',
symbol: 'USD',
decimals: 6,
},
rpcUrls: {
default: {
http: [`https://rpc-zone-${paddedId}.${options.rpcHost}`],
},
},
sourceId: options.sourceId,
})
}
}
declare namespace from {
type Options = {
/** RPC hostname used to construct zone RPC URLs (e.g. `tempo.xyz`). */
rpcHost: string
/** Chain ID of the parent Tempo chain (e.g. `4217` for mainnet, `42431` for moderato). */
sourceId: number
}
}