Skip to content

Read & Write Allowance

Concurrently read token metadata, ablance, and allowance.

import {
class DirectSecp256k1HdWallet

A wallet for protobuf based signing using SIGN_MODE_DIRECT

DirectSecp256k1HdWallet
} from "@cosmjs/proto-signing"
import {
class GasPrice

A gas price, i.e. the price of a single unit of gas. This is typically a fraction of the smallest fee token unit, such as 0.012utoken.

GasPrice
} from "@cosmjs/stargate"
import {
import Cosmos
Cosmos
,
import Ucs05
Ucs05
} from "@unionlabs/sdk"
import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const RPC_URL: "https://rpc.union-testnet-10.union.chain.kitchen"
RPC_URL
= "https://rpc.union-testnet-10.union.chain.kitchen"
const
const wallet: DirectSecp256k1HdWallet
wallet
= await
class DirectSecp256k1HdWallet

A wallet for protobuf based signing using SIGN_MODE_DIRECT

DirectSecp256k1HdWallet
.
DirectSecp256k1HdWallet.fromMnemonic(mnemonic: string, options?: Partial<DirectSecp256k1HdWalletOptions>): Promise<DirectSecp256k1HdWallet>

Restores a wallet from the given BIP39 mnemonic.

@parammnemonic Any valid English mnemonic.

@paramoptions An optional DirectSecp256k1HdWalletOptions object optionally containing a bip39Password, hdPaths, and prefix.

fromMnemonic
("memo memo memo", {
prefix?: string

The bech32 address prefix (human readable part). Defaults to "cosmos".

prefix
: "union" })
const [
const account: AccountData
account
] = await
const wallet: DirectSecp256k1HdWallet
wallet
.
DirectSecp256k1HdWallet.getAccounts(): Promise<readonly AccountData[]>
getAccounts
()
const
const client: Layer<Cosmos.Client, Cosmos.ClientError, never>
client
=
import Cosmos
Cosmos
.
class Client

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

@since2.0.0

Client
.
Client.Live: (endpoint: string | HttpEndpoint) => Layer<Cosmos.Client, Cosmos.ClientError, never>
Live
(
const RPC_URL: "https://rpc.union-testnet-10.union.chain.kitchen"
RPC_URL
)
const
const signingClient: Layer<Cosmos.SigningClient, Cosmos.ClientError, never>
signingClient
=
import Cosmos
Cosmos
.
class SigningClient

Context for providing a SigningCosmWasmClient

@since2.0.0

SigningClient
.
SigningClient.Live: (endpoint: string | HttpEndpoint, signer: OfflineSigner, options?: SigningCosmWasmClientOptions | undefined) => Layer<...>
Live
(
const RPC_URL: "https://rpc.union-testnet-10.union.chain.kitchen"
RPC_URL
,
const wallet: DirectSecp256k1HdWallet
wallet
,
{
SigningCosmWasmClientOptions.gasPrice?: GasPrice
gasPrice
:
class GasPrice

A gas price, i.e. the price of a single unit of gas. This is typically a fraction of the smallest fee token unit, such as 0.012utoken.

GasPrice
.
GasPrice.fromString(gasPrice: string): GasPrice

Parses a gas price formatted as <amount><denom>, e.g. GasPrice.fromString("0.012utoken").

The denom must match the Cosmos SDK 0.42 pattern (https://github.com/cosmos/cosmos-sdk/blob/v0.42.4/types/coin.go#L599-L601). See GasPrice in

fromString
("0.025muno") },
)
const
const program: Effect.Effect<void, Cosmos.ClientError | TimeoutException | Cosmos.QueryContractError | Cosmos.ExecuteContractError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<number, TimeoutException | Cosmos.QueryContractError, Cosmos.Client>> | YieldWrap<Effect.Effect<ExecuteResult, Cosmos.ExecuteContractError, Cosmos.SigningClient>>, void>(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 contractAddress: `${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">
contractAddress
=
import Ucs05
Ucs05
.
const AddressCosmosDisplay: brand<filter<brand<TemplateLiteral<`${string}1${string}`>, "Bech32">>, "AddressCosmosDisplay">

@since2.0.0

@since2.0.0

AddressCosmosDisplay
.
BrandSchema<`${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">, `${string}1${string}`, never>.make(a: `${string}1${string}`, options?: MakeOptions): `${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">
make
(
"union13pxktu2hk8pseksaaka54ngxyfmpjljrleh3cc8sxvq4dxalvttqdmdgv5",
)
const
const spender: `${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">
spender
=
import Ucs05
Ucs05
.
const AddressCosmosDisplay: brand<filter<brand<TemplateLiteral<`${string}1${string}`>, "Bech32">>, "AddressCosmosDisplay">

@since2.0.0

@since2.0.0

AddressCosmosDisplay
.
BrandSchema<`${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">, `${string}1${string}`, never>.make(a: `${string}1${string}`, options?: MakeOptions): `${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">
make
(
"union1x2jzeup7uwfxjxxrtfna2ktcugltntgu6kvc0eeayk0d82l247cqz669ee",
)
const
const allowance: number
allowance
= yield*
import Cosmos
Cosmos
.
const readCw20Allowance: (contract: AddressCosmosDisplay, owner: AddressCosmosDisplay, spender: AddressCosmosDisplay) => Effect.Effect<...>

Read the allowance of a CW20 token for a specific addresses

@paramcontract The address of the CW20 token contract

@paramowner The owner of the token

@paramspender The spender who will spend the token

@returnsAn Effect that resolves to the token allowance

@since2.0.0

readCw20Allowance
(
const contractAddress: `${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">
contractAddress
,
const account: AccountData
account
.
AccountData.address: string

A printable address (typically bech32 encoded)

address
as unknown as any,
const spender: `${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">
spender
,
)
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.info(message?: any, ...optionalParams: any[]): void (+1 overload)

The console.info() function is an alias for

log

.

@sincev0.1.100

info
("Current allowance:",
const allowance: number
allowance
.
Number.toString(radix?: number): string

Returns a string representation of an object.

@paramradix Specifies a radix for converting numeric values to strings. This value is only used for numbers.

toString
())
yield*
import Cosmos
Cosmos
.
const writeCw20IncreaseAllowance: (contractAddress: string, senderAddress: string, spenderAddress: string, amount: string) => Effect.Effect<ExecuteResult, Cosmos.ExecuteContractError, Cosmos.SigningClient>

Increase the allowance of a CW20 token for a specific spender.

@paramcontractAddress The address of the CW20 token contract.

@paramsenderAddress The address of the token owner (the one increasing the allowance).

@paramspenderAddress The address of the spender who is allowed to spend the tokens.

@paramamount The amount by which to increase the allowance (as a string).

@paramexpires Optional expiration for the increased allowance.

@returnsAn Effect that resolves to the execution result.

@since2.0.0

writeCw20IncreaseAllowance
(
const contractAddress: `${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">
contractAddress
,
const account: AccountData
account
.
AccountData.address: string

A printable address (typically bech32 encoded)

address
,
const spender: `${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">
spender
, "1")
const
const allowance_after: number
allowance_after
= yield*
import Cosmos
Cosmos
.
const readCw20Allowance: (contract: AddressCosmosDisplay, owner: AddressCosmosDisplay, spender: AddressCosmosDisplay) => Effect.Effect<...>

Read the allowance of a CW20 token for a specific addresses

@paramcontract The address of the CW20 token contract

@paramowner The owner of the token

@paramspender The spender who will spend the token

@returnsAn Effect that resolves to the token allowance

@since2.0.0

readCw20Allowance
(
const contractAddress: `${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">
contractAddress
,
import Ucs05
Ucs05
.
const AddressCosmosDisplay: brand<filter<brand<TemplateLiteral<`${string}1${string}`>, "Bech32">>, "AddressCosmosDisplay">

@since2.0.0

@since2.0.0

AddressCosmosDisplay
.
BrandSchema<`${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">, `${string}1${string}`, never>.make(a: `${string}1${string}`, options?: MakeOptions): `${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">
make
(
const account: AccountData
account
.
AccountData.address: string

A printable address (typically bech32 encoded)

address
as unknown as any),
const spender: `${string}1${string}` & Brand<"Bech32"> & Brand<"AddressCosmosDisplay">
spender
,
)
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.info(message?: any, ...optionalParams: any[]): void (+1 overload)

The console.info() function is an alias for

log

.

@sincev0.1.100

info
("allowance after increasing:",
const allowance_after: number
allowance_after
.
Number.toString(radix?: number): string

Returns a string representation of an object.

@paramradix Specifies a radix for converting numeric values to strings. This value is only used for numbers.

toString
())
}).
Pipeable.pipe<Effect.Effect<void, TimeoutException | Cosmos.QueryContractError | Cosmos.ExecuteContractError, Cosmos.Client | Cosmos.SigningClient>, 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: <Cosmos.Client, Cosmos.ClientError, never>(layer: Layer<Cosmos.Client, Cosmos.ClientError, 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<Cosmos.Client, Cosmos.ClientError, never>
client
),
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const provide: <Cosmos.SigningClient, Cosmos.ClientError, never>(layer: Layer<Cosmos.SigningClient, Cosmos.ClientError, never>) => <A, E, R>(self: Effect.Effect<...>) => 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 signingClient: Layer<Cosmos.SigningClient, Cosmos.ClientError, never>
signingClient
),
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, Cosmos.ClientError | TimeoutException | Cosmos.QueryContractError | Cosmos.ExecuteContractError>(effect: Effect.Effect<void, Cosmos.ClientError | TimeoutException | Cosmos.QueryContractError | Cosmos.ExecuteContractError, never>, 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<void, Cosmos.ClientError | TimeoutException | Cosmos.QueryContractError | Cosmos.ExecuteContractError, never>
program
)
.
Promise<void>.then<void, never>(onfulfilled?: ((value: void) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | 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
)