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

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