Skip to content

ERC20 Increase Allowance

Allowance on Sepolia for USDC spending is increased by 1 atomic unit.

import {
import Evm
Evm
} from "@unionlabs/sdk"
import {
type UniversalChainId = string & Brand<"UniversalChainId">
const UniversalChainId: brand<filter<typeof String$>, "UniversalChainId">
UniversalChainId
} from "@unionlabs/sdk/schema/chain"
import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
import {
function http<rpcSchema extends RpcSchema | undefined = undefined, raw extends boolean = false>(url?: string | undefined, config?: HttpTransportConfig<rpcSchema, raw>): HttpTransport<rpcSchema, raw>

@description Creates a HTTP transport that connects to a JSON-RPC API.

http
} from "viem"
import {
function privateKeyToAccount(privateKey: Hex, options?: PrivateKeyToAccountOptions): PrivateKeyAccount

@description Creates an Account from a private key.

@returnsA Private Key Account.

privateKeyToAccount
} from "viem/accounts"
import {
const sepolia: {
blockExplorers: {
readonly default: {
readonly name: "Etherscan";
readonly url: "https://sepolia.etherscan.io";
readonly apiUrl: "https://api-sepolia.etherscan.io/api";
};
};
... 11 more ...;
serializers?: ChainSerializers<...> | undefined;
}
sepolia
} from "viem/chains"
const
const account: {
address: Address;
nonceManager?: NonceManager | undefined;
sign: (parameters: {
hash: Hash;
}) => Promise<Hex>;
... 6 more ...;
type: "local";
}
account
=
function privateKeyToAccount(privateKey: Hex, options?: PrivateKeyToAccountOptions): PrivateKeyAccount

@description Creates an Account from a private key.

@returnsA Private Key Account.

privateKeyToAccount
("0x...")
const
const wallet: Layer<Evm.WalletClient, Evm.CreateWalletClientError, never>
wallet
=
import Evm
Evm
.
class WalletClient

A wallet client that can be used for signing transactions

@since2.0.0

WalletClient
.
WalletClient.Live: (options: Parameters<typeof createWalletClient>[0] & {
account: Account;
chain: Chain;
}) => Layer<...>
Live
({
account: {
client: Client;
entryPoint: {
abi: Abi;
address: Address;
version: EntryPointVersion;
};
extend?: object | undefined;
getAddress: () => Promise<Address>;
... 18 more ...;
source?: undefined;
} | ... 4 more ... | (`0x${string}` & {
...;
})

The Account to use for the Client. This will be used for Actions that require an account as an argument.

account
,
chain: {
blockExplorers?: {
[key: string]: ChainBlockExplorer;
default: ChainBlockExplorer;
} | undefined;
... 7 more ...;
testnet?: boolean | undefined;
} & ChainConfig<...>

Chain for the client.

chain
:
const sepolia: {
blockExplorers: {
readonly default: {
readonly name: "Etherscan";
readonly url: "https://sepolia.etherscan.io";
readonly apiUrl: "https://api-sepolia.etherscan.io/api";
};
};
... 11 more ...;
serializers?: ChainSerializers<...> | undefined;
}
sepolia
,
transport: Transport

The RPC transport

transport
:
http<undefined, false>(url?: string | undefined, config?: HttpTransportConfig<undefined, false> | undefined): HttpTransport<undefined, false>

@description Creates a HTTP transport that connects to a JSON-RPC API.

http
(),
})
const
const client: Layer<Evm.PublicClient, Evm.CreatePublicClientError, never>
client
=
import Evm
Evm
.
class PublicClient

A neutral public client that can be used for general-purpose operations that don't specifically target source or destination chains

@since2.0.0

PublicClient
.
PublicClient.Live: (parameters: {
cacheTime?: number | undefined | undefined;
ccipRead?: {
request?: (parameters: CcipRequestParameters) => Promise<CcipRequestReturnType>;
} | false | undefined | undefined;
... 6 more ...;
batch?: {
multicall?: boolean | Prettify<MulticallBatchOptions> | undefined;
} | undefined | undefined;
}) => Layer<...>
Live
({
chain?: Chain | undefined

Chain for the client.

chain
:
const sepolia: {
blockExplorers: {
readonly default: {
readonly name: "Etherscan";
readonly url: "https://sepolia.etherscan.io";
readonly apiUrl: "https://api-sepolia.etherscan.io/api";
};
};
... 11 more ...;
serializers?: ChainSerializers<...> | undefined;
}
sepolia
,
transport: Transport

The RPC transport

transport
:
http<undefined, false>(url?: string | undefined, config?: HttpTransportConfig<undefined, false> | undefined): HttpTransport<undefined, false>

@description Creates a HTTP transport that connects to a JSON-RPC API.

http
(),
})
const
const TOKEN_ADDRESS: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"
TOKEN_ADDRESS
= "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238" // USDC on Sepolia
const
const SPENDER_ADDRESS: "0x5fbe74a283f7954f10aa04c2edf55578811aeb03"
SPENDER_ADDRESS
= "0x5fbe74a283f7954f10aa04c2edf55578811aeb03" // UCS03 on Sepolia
const
const readAllowance: Effect.Effect<bigint, Evm.ReadContractError, Evm.PublicClient>
readAllowance
=
import Evm
Evm
.
const readErc20Allowance: (tokenAddress: Address, ownerAddress: Address, spenderAddress: Address) => Effect.Effect<bigint, Evm.ReadContractError, Evm.PublicClient>

Read the allowance of an ERC20 token for a specific owner and spender

@paramtokenAddress The address of the ERC20 token

@paramownerAddress The address of the token owner

@paramspenderAddress The address of the spender

@returnsAn Effect that resolves to the token allowance

@since2.0.0

readErc20Allowance
(
const TOKEN_ADDRESS: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"
TOKEN_ADDRESS
,
const account: {
address: Address;
nonceManager?: NonceManager | undefined;
sign: (parameters: {
hash: Hash;
}) => Promise<Hex>;
... 6 more ...;
type: "local";
}
account
.
address: `0x${string}`
address
,
const SPENDER_ADDRESS: "0x5fbe74a283f7954f10aa04c2edf55578811aeb03"
SPENDER_ADDRESS
,
)
const
const readMeta: Effect.Effect<{
name: string;
symbol: string;
decimals: number;
}, Evm.ReadContractError, Evm.PublicClient>
readMeta
=
import Evm
Evm
.
const readErc20Meta: (tokenAddress: Address, chainId: UniversalChainId) => Effect.Effect<{
name: string;
symbol: string;
decimals: number;
}, Evm.ReadContractError, Evm.PublicClient>

Read ERC20 token metadata (name, symbol, decimals)

@paramtokenAddress The address of the ERC20 token

@paramchainId The Universal chain ID to check for gas denomination

@returnsAn Effect that resolves to the token metadata

@since2.0.0

readErc20Meta
(
const TOKEN_ADDRESS: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"
TOKEN_ADDRESS
,
const UniversalChainId: brand<filter<typeof String$>, "UniversalChainId">
UniversalChainId
.
BrandSchema<string & Brand<"UniversalChainId">, string, never>.make(a: string, options?: MakeOptions): string & Brand<"UniversalChainId">
make
("ethereum.11155111"),
)
const
const increaseAllowance: (amount: bigint) => Effect.Effect.AsEffect<Effect.Effect<`0x${string}`, Evm.WriteContractError, Evm.WalletClient>>
increaseAllowance
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const fn: <Effect.Effect<`0x${string}`, Evm.WriteContractError, Evm.WalletClient>, [amount: bigint]>(body: (amount: bigint) => Effect.Effect<`0x${string}`, Evm.WriteContractError, Evm.WalletClient>) => (amount: bigint) => Effect.Effect<out A, out E = never, out R = never>.AsEffect<...> (+20 overloads)
fn
(
(
amount: bigint
amount
: bigint) =>
import Evm
Evm
.
const increaseErc20Allowance: (tokenAddress: Address, spenderAddress: Address, amount: bigint) => Effect.Effect<`0x${string}`, Evm.WriteContractError, Evm.WalletClient>

Increase the allowance of an ERC20 token for a specific spender

@paramtokenAddress The address of the ERC20 token

@paramspenderAddress The address of the spender

@paramamount The amount to increase the allowance by

@returnsAn Effect that resolves to the transaction hash

@since2.0.0

increaseErc20Allowance
(
const TOKEN_ADDRESS: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"
TOKEN_ADDRESS
,
const SPENDER_ADDRESS: "0x5fbe74a283f7954f10aa04c2edf55578811aeb03"
SPENDER_ADDRESS
,
amount: bigint
amount
),
)
const
const program: Effect.Effect<{
previousAllowance: bigint;
newAllowance: bigint;
transactionHash: `0x${string}`;
receipt: {
blockNumber: bigint;
status: "success" | "reverted";
};
name: string;
symbol: string;
decimals: number;
}, Evm.CreateWalletClientError | ... 3 more ... | Evm.WaitForTransactionReceiptError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<`0x${string}`, Evm.WriteContractError, Evm.WalletClient>> | YieldWrap<Effect.Effect<{
name: string;
symbol: string;
decimals: number;
}, Evm.ReadContractError, Evm.PublicClient>> | YieldWrap<...> | YieldWrap<...> | YieldWrap<...>, {
...;
}>(f: (resume: Effect.Adapter) => Generator<...>) => Effect.Effect<...> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function*() {
const
const currentAllowance: bigint
currentAllowance
= yield*
const readAllowance: Effect.Effect<bigint, Evm.ReadContractError, Evm.PublicClient>
readAllowance
yield*
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const log: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never>

Logs one or more messages or error causes at the current log level.

Details

This function provides a simple way to log messages or error causes during the execution of your effects. By default, logs are recorded at the INFO level, but this can be adjusted using other logging utilities (Logger.withMinimumLogLevel). Multiple items, including Cause instances, can be logged in a single call. When logging Cause instances, detailed error information is included in the log output.

The log output includes useful metadata like the current timestamp, log level, and fiber ID, making it suitable for debugging and tracking purposes. This function does not interrupt or alter the effect's execution flow.

Example

import { Cause, Effect } from "effect"
const program = Effect.log(
"message1",
"message2",
Cause.die("Oh no!"),
Cause.die("Oh uh!")
)
Effect.runFork(program)
// Output:
// timestamp=... level=INFO fiber=#0 message=message1 message=message2 cause="Error: Oh no!
// Error: Oh uh!"

@since2.0.0

log
(`Current allowance: ${
const currentAllowance: bigint
currentAllowance
}`)
yield*
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const log: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never>

Logs one or more messages or error causes at the current log level.

Details

This function provides a simple way to log messages or error causes during the execution of your effects. By default, logs are recorded at the INFO level, but this can be adjusted using other logging utilities (Logger.withMinimumLogLevel). Multiple items, including Cause instances, can be logged in a single call. When logging Cause instances, detailed error information is included in the log output.

The log output includes useful metadata like the current timestamp, log level, and fiber ID, making it suitable for debugging and tracking purposes. This function does not interrupt or alter the effect's execution flow.

Example

import { Cause, Effect } from "effect"
const program = Effect.log(
"message1",
"message2",
Cause.die("Oh no!"),
Cause.die("Oh uh!")
)
Effect.runFork(program)
// Output:
// timestamp=... level=INFO fiber=#0 message=message1 message=message2 cause="Error: Oh no!
// Error: Oh uh!"

@since2.0.0

log
(`Increasing allowance...`)
const
const txHash: `0x${string}`
txHash
= yield*
const increaseAllowance: (amount: bigint) => Effect.Effect<out A, out E = never, out R = never>.AsEffect<Effect.Effect<`0x${string}`, Evm.WriteContractError, Evm.WalletClient>>
increaseAllowance
(
const currentAllowance: bigint
currentAllowance
+ 1n)
yield*
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const log: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never>

Logs one or more messages or error causes at the current log level.

Details

This function provides a simple way to log messages or error causes during the execution of your effects. By default, logs are recorded at the INFO level, but this can be adjusted using other logging utilities (Logger.withMinimumLogLevel). Multiple items, including Cause instances, can be logged in a single call. When logging Cause instances, detailed error information is included in the log output.

The log output includes useful metadata like the current timestamp, log level, and fiber ID, making it suitable for debugging and tracking purposes. This function does not interrupt or alter the effect's execution flow.

Example

import { Cause, Effect } from "effect"
const program = Effect.log(
"message1",
"message2",
Cause.die("Oh no!"),
Cause.die("Oh uh!")
)
Effect.runFork(program)
// Output:
// timestamp=... level=INFO fiber=#0 message=message1 message=message2 cause="Error: Oh no!
// Error: Oh uh!"

@since2.0.0

log
(`Waiting for transaction ${
const txHash: `0x${string}`
txHash
}...`)
const
const receipt: TransactionReceipt
receipt
= yield*
import Evm
Evm
.
const waitForTransactionReceipt: (hash: Hash) => Effect.Effect<TransactionReceipt, Evm.WaitForTransactionReceiptError, Evm.PublicClient>

Wait for a transaction receipt

@paramhash The transaction hash for which to wait

@returnsAn Effect that resolves to the transaction receipt

@since2.0.0

waitForTransactionReceipt
(
const txHash: `0x${string}`
txHash
)
yield*
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const log: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never>

Logs one or more messages or error causes at the current log level.

Details

This function provides a simple way to log messages or error causes during the execution of your effects. By default, logs are recorded at the INFO level, but this can be adjusted using other logging utilities (Logger.withMinimumLogLevel). Multiple items, including Cause instances, can be logged in a single call. When logging Cause instances, detailed error information is included in the log output.

The log output includes useful metadata like the current timestamp, log level, and fiber ID, making it suitable for debugging and tracking purposes. This function does not interrupt or alter the effect's execution flow.

Example

import { Cause, Effect } from "effect"
const program = Effect.log(
"message1",
"message2",
Cause.die("Oh no!"),
Cause.die("Oh uh!")
)
Effect.runFork(program)
// Output:
// timestamp=... level=INFO fiber=#0 message=message1 message=message2 cause="Error: Oh no!
// Error: Oh uh!"

@since2.0.0

log
(`Transaction confirmed in block: ${
const receipt: TransactionReceipt
receipt
.
blockNumber: bigint

Number of block containing this transaction

blockNumber
}`)
const
const newAllowance: bigint
newAllowance
= yield*
const readAllowance: Effect.Effect<bigint, Evm.ReadContractError, Evm.PublicClient>
readAllowance
return {
...(yield*
const readMeta: Effect.Effect<{
name: string;
symbol: string;
decimals: number;
}, Evm.ReadContractError, Evm.PublicClient>
readMeta
),
previousAllowance: bigint
previousAllowance
:
const currentAllowance: bigint
currentAllowance
,
newAllowance: bigint
newAllowance
,
transactionHash: `0x${string}`
transactionHash
:
const txHash: `0x${string}`
txHash
,
receipt: {
blockNumber: bigint;
status: "success" | "reverted";
}
receipt
: {
blockNumber: bigint
blockNumber
:
const receipt: TransactionReceipt
receipt
.
blockNumber: bigint

Number of block containing this transaction

blockNumber
,
status: "success" | "reverted"
status
:
const receipt: TransactionReceipt
receipt
.
status: "success" | "reverted"

success if this transaction was successful or reverted if it failed

status
,
},
}
}).
Pipeable.pipe<Effect.Effect<{
previousAllowance: bigint;
newAllowance: bigint;
transactionHash: `0x${string}`;
receipt: {
blockNumber: bigint;
status: "success" | "reverted";
};
name: string;
symbol: string;
decimals: number;
}, Evm.ReadContractError | ... 1 more ... | Evm.WaitForTransactionReceiptError, Evm.WalletClient | Evm.PublicClient>, Effect.Effect<...>, Effect.Effect<...>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>, bc: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const provide: <Evm.PublicClient, Evm.CreatePublicClientError, never>(layer: Layer<Evm.PublicClient, Evm.CreatePublicClientError, never>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<...> (+9 overloads)

Provides necessary dependencies to an effect, removing its environmental requirements.

Details

This function allows you to supply the required environment for an effect. The environment can be provided in the form of one or more Layers, a Context, a Runtime, or a ManagedRuntime. Once the environment is provided, the effect can run without requiring external dependencies.

You can compose layers to create a modular and reusable way of setting up the environment for effects. For example, layers can be used to configure databases, logging services, or any other required dependencies.

Example

import { Context, Effect, Layer } from "effect"
class Database extends Context.Tag("Database")<
Database,
{ readonly query: (sql: string) => Effect.Effect<Array<unknown>> }
>() {}
const DatabaseLive = Layer.succeed(
Database,
{
// Simulate a database query
query: (sql: string) => Effect.log(`Executing query: ${sql}`).pipe(Effect.as([]))
}
)
// ┌─── Effect<unknown[], never, Database>
// ▼
const program = Effect.gen(function*() {
const database = yield* Database
const result = yield* database.query("SELECT * FROM users")
return result
})
// ┌─── Effect<unknown[], never, never>
// ▼
const runnable = Effect.provide(program, DatabaseLive)
Effect.runPromise(runnable).then(console.log)
// Output:
// timestamp=... level=INFO fiber=#0 message="Executing query: SELECT * FROM users"
// []

@seeprovideService for providing a service to an effect.

@since2.0.0

provide
(
const client: Layer<Evm.PublicClient, Evm.CreatePublicClientError, never>
client
),
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const provide: <Evm.WalletClient, Evm.CreateWalletClientError, never>(layer: Layer<Evm.WalletClient, Evm.CreateWalletClientError, never>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<...> (+9 overloads)

Provides necessary dependencies to an effect, removing its environmental requirements.

Details

This function allows you to supply the required environment for an effect. The environment can be provided in the form of one or more Layers, a Context, a Runtime, or a ManagedRuntime. Once the environment is provided, the effect can run without requiring external dependencies.

You can compose layers to create a modular and reusable way of setting up the environment for effects. For example, layers can be used to configure databases, logging services, or any other required dependencies.

Example

import { Context, Effect, Layer } from "effect"
class Database extends Context.Tag("Database")<
Database,
{ readonly query: (sql: string) => Effect.Effect<Array<unknown>> }
>() {}
const DatabaseLive = Layer.succeed(
Database,
{
// Simulate a database query
query: (sql: string) => Effect.log(`Executing query: ${sql}`).pipe(Effect.as([]))
}
)
// ┌─── Effect<unknown[], never, Database>
// ▼
const program = Effect.gen(function*() {
const database = yield* Database
const result = yield* database.query("SELECT * FROM users")
return result
})
// ┌─── Effect<unknown[], never, never>
// ▼
const runnable = Effect.provide(program, DatabaseLive)
Effect.runPromise(runnable).then(console.log)
// Output:
// timestamp=... level=INFO fiber=#0 message="Executing query: SELECT * FROM users"
// []

@seeprovideService for providing a service to an effect.

@since2.0.0

provide
(
const wallet: Layer<Evm.WalletClient, Evm.CreateWalletClientError, never>
wallet
),
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <{
previousAllowance: bigint;
newAllowance: bigint;
transactionHash: `0x${string}`;
receipt: {
blockNumber: bigint;
status: "success" | "reverted";
};
name: string;
symbol: string;
decimals: number;
}, Evm.CreateWalletClientError | ... 3 more ... | Evm.WaitForTransactionReceiptError>(effect: Effect.Effect<...>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<{
previousAllowance: bigint;
newAllowance: bigint;
transactionHash: `0x${string}`;
receipt: {
blockNumber: bigint;
status: "success" | "reverted";
};
name: string;
symbol: string;
decimals: number;
}, Evm.CreateWalletClientError | ... 3 more ... | Evm.WaitForTransactionReceiptError, never>
program
)
.
Promise<{ previousAllowance: bigint; newAllowance: bigint; transactionHash: `0x${string}`; receipt: { blockNumber: bigint; status: "success" | "reverted"; }; name: string; symbol: string; decimals: number; }>.then<void, never>(onfulfilled?: ((value: {
previousAllowance: bigint;
newAllowance: bigint;
transactionHash: `0x${string}`;
receipt: {
blockNumber: bigint;
status: "success" | "reverted";
};
name: string;
symbol: string;
decimals: number;
}) => void | PromiseLike<...>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | ... 1 more ... | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(...data: any[]): void (+1 overload)
log
)
.
Promise<void>.catch<void>(onrejected?: ((reason: any) => void | PromiseLike<void>) | null | undefined): Promise<void>

Attaches a callback for only the rejection of the Promise.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of the callback.

catch
(
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.error(...data: any[]): void (+1 overload)

Log to stderr in your terminal

Appears in red

@paramdata something to display

error
)