viem
Version:
1,585 lines • 97.6 kB
JavaScript
import * as Hex from 'ox/Hex';
import { TokenId, TokenRole } from 'ox/tempo';
import { parseAccount } from '../../accounts/utils/parseAccount.js';
import { estimateContractGas } from '../../actions/public/estimateContractGas.js';
import { multicall } from '../../actions/public/multicall.js';
import { readContract } from '../../actions/public/readContract.js';
import { simulateContract, } from '../../actions/public/simulateContract.js';
import { watchContractEvent } from '../../actions/public/watchContractEvent.js';
import * as internal_Token from '../../actions/token/internal.js';
import { sendTransaction } from '../../actions/wallet/sendTransaction.js';
import { sendTransactionSync, } from '../../actions/wallet/sendTransactionSync.js';
import { writeContract } from '../../actions/wallet/writeContract.js';
import { writeContractSync } from '../../actions/wallet/writeContractSync.js';
import { AccountNotFoundError } from '../../errors/account.js';
import { encodeFunctionData } from '../../utils/abi/encodeFunctionData.js';
import { parseEventLogs } from '../../utils/abi/parseEventLogs.js';
import { formatUnits } from '../../utils/unit/formatUnits.js';
import * as Abis from '../Abis.js';
import * as Addresses from '../Addresses.js';
import { defineCall, findDeclaredToken, pickWriteParameters, resolveCallParameters, resolveToken, resolveTokenWithDecimals, } from '../internal/utils.js';
/**
* Approves a spender to transfer TIP20 tokens on behalf of the caller.
*
* @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.token.approve(client, {
* spender: '0x...',
* amount: 100n,
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function approve(client, parameters) {
return approve.inner(writeContract, client, parameters);
}
(function (approve) {
/** @internal */
async function inner(action, client, parameters) {
return (await action(client, {
...parameters,
...approve.call(client, parameters),
}));
}
approve.inner = inner;
/**
* Defines a call to the `approve` function.
*
* Can be passed as a parameter to `estimateContractGas`, `simulateContract`,
* `sendCalls`, `sendTransaction` (`calls`), or `multicall`. The token is
* selected by `token`, which is either a TIP20 token id or a contract
* `address`; `amount.decimals` is inferred from the client's declared
* `tokens` when omitted.
*
* @param parameters - Client (optional), followed by the call arguments.
* @returns The call.
*/
function call(...parameters) {
const [client, args] = resolveCallParameters(parameters);
const { amount, spender, token } = args;
const { address, decimals } = resolveToken(client, { token });
return defineCall({
address,
abi: Abis.tip20,
functionName: 'approve',
args: [spender, internal_Token.toBaseUnits(amount, decimals)],
});
}
approve.call = call;
/**
* Estimates the gas required to approve a spender. `amount.decimals` is
* inferred from the client's declared `tokens` when omitted.
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The gas estimate.
*/
async function estimateGas(client, parameters) {
return estimateContractGas(client, {
...pickWriteParameters(parameters),
...approve.call(client, parameters),
});
}
approve.estimateGas = estimateGas;
/**
* Simulates an approval of a spender. `amount.decimals` is inferred from
* the client's declared `tokens` when omitted.
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The simulation result and write request.
*/
async function simulate(client, parameters) {
return simulateContract(client, {
...pickWriteParameters(parameters),
...approve.call(client, parameters),
});
}
approve.simulate = simulate;
/**
* Extracts the `Approval` event from logs.
*
* @param logs - The logs.
* @returns The `Approval` event.
*/
function extractEvent(logs) {
const [log] = parseEventLogs({
abi: Abis.tip20,
logs,
eventName: 'Approval',
});
if (!log)
throw new Error('`Approval` event not found.');
return log;
}
approve.extractEvent = extractEvent;
})(approve || (approve = {}));
/**
* Approves a spender to transfer TIP20 tokens on behalf of the caller.
*
* @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.token.approveSync(client, {
* spender: '0x...',
* amount: 100n,
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and event data.
*/
export async function approveSync(client, parameters) {
const { amount, token, throwOnReceiptRevert = true } = parameters;
const { decimals } = resolveToken(client, { token });
const resolved = internal_Token.resolveAmountDecimals(amount, decimals);
const receipt = await approve.inner(writeContractSync, client, {
...parameters,
throwOnReceiptRevert,
});
const { args } = approve.extractEvent(receipt.logs);
return {
...args,
...(resolved === undefined
? {}
: { decimals: resolved, formatted: formatUnits(args.amount, resolved) }),
receipt,
};
}
/**
* Burns TIP20 tokens from a blocked 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 result = await Actions.token.burnBlocked(client, {
* from: '0x...',
* amount: 100n,
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function burnBlocked(client, parameters) {
return burnBlocked.inner(writeContract, client, parameters);
}
(function (burnBlocked) {
/** @internal */
async function inner(action, client, parameters) {
const { amount, from, token, ...rest } = parameters;
const call = burnBlocked.call(client, { amount, from, token });
return (await action(client, {
...rest,
...call,
}));
}
burnBlocked.inner = inner;
/**
* Defines a call to the `burnBlocked` 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.token.burnBlocked.call(client, {
* from: '0x20c0...beef',
* amount: 100n,
* token: '0x20c0...babe',
* }),
* ]
* })
* ```
*
* `amount.decimals` is inferred from the client's declared `tokens` when omitted.
*
* @param parameters - Client (optional), followed by the call arguments.
* @returns The call.
*/
function call(...parameters) {
const [client, args] = resolveCallParameters(parameters);
const { from, amount, token } = args;
const { address, decimals } = resolveToken(client, { token });
return defineCall({
address,
abi: Abis.tip20,
functionName: 'burnBlocked',
args: [from, internal_Token.toBaseUnits(amount, decimals)],
});
}
burnBlocked.call = call;
/**
* Extracts the event from the logs.
*
* @param logs - Logs.
* @returns The event.
*/
function extractEvent(logs) {
const [log] = parseEventLogs({
abi: Abis.tip20,
logs,
eventName: 'BurnBlocked',
});
if (!log)
throw new Error('`BurnBlocked` event not found.');
return log;
}
burnBlocked.extractEvent = extractEvent;
})(burnBlocked || (burnBlocked = {}));
/**
* Burns TIP20 tokens from a blocked 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 result = await Actions.token.burnBlockedSync(client, {
* from: '0x...',
* amount: 100n,
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and event data.
*/
export async function burnBlockedSync(client, parameters) {
const { throwOnReceiptRevert = true, ...rest } = parameters;
const receipt = await burnBlocked.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
});
const { args } = burnBlocked.extractEvent(receipt.logs);
return {
...args,
receipt,
};
}
/**
* Burns TIP20 tokens from the caller'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 result = await Actions.token.burn(client, {
* amount: 100n,
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function burn(client, parameters) {
return burn.inner(writeContract, client, parameters);
}
(function (burn) {
/** @internal */
async function inner(action, client, parameters) {
const { amount, memo, token, ...rest } = parameters;
const call = burn.call(client, { amount, memo, token });
return (await action(client, {
...rest,
...call,
}));
}
burn.inner = inner;
/**
* Defines a call to the `burn` or `burnWithMemo` 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.token.burn.call(client, {
* amount: 100n,
* token: '0x20c0...babe',
* }),
* ]
* })
* ```
*
* `amount.decimals` is inferred from the client's declared `tokens` when omitted.
*
* @param parameters - Client (optional), followed by the call arguments.
* @returns The call.
*/
function call(...parameters) {
const [client, args] = resolveCallParameters(parameters);
const { amount, memo, token } = args;
const { address, decimals } = resolveToken(client, { token });
const value = internal_Token.toBaseUnits(amount, decimals);
const callArgs = memo
? {
functionName: 'burnWithMemo',
args: [value, Hex.padLeft(memo, 32)],
}
: {
functionName: 'burn',
args: [value],
};
return defineCall({
address,
abi: Abis.tip20,
...callArgs,
});
}
burn.call = call;
/**
* Extracts the event from the logs.
*
* @param logs - Logs.
* @returns The event.
*/
function extractEvent(logs) {
const [log] = parseEventLogs({
abi: Abis.tip20,
logs,
eventName: 'Burn',
});
if (!log)
throw new Error('`Burn` event not found.');
return log;
}
burn.extractEvent = extractEvent;
})(burn || (burn = {}));
/**
* Burns TIP20 tokens from the caller'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 result = await Actions.token.burnSync(client, {
* amount: 100n,
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and event data.
*/
export async function burnSync(client, parameters) {
const { throwOnReceiptRevert = true, ...rest } = parameters;
const receipt = await burn.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
});
const { args } = burn.extractEvent(receipt.logs);
return {
...args,
receipt,
};
}
/**
* Changes the transfer policy ID for a TIP20 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.token.changeTransferPolicy(client, {
* token: '0x...',
* policyId: 1n,
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function changeTransferPolicy(client, parameters) {
return changeTransferPolicy.inner(writeContract, client, parameters);
}
(function (changeTransferPolicy) {
/** @internal */
async function inner(action, client, parameters) {
const { policyId, token, ...rest } = parameters;
const call = changeTransferPolicy.call(client, { policyId, token });
return (await action(client, {
...rest,
...call,
}));
}
changeTransferPolicy.inner = inner;
/**
* Defines a call to the `changeTransferPolicyId` 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.token.changeTransferPolicy.call(client, {
* token: '0x20c0...babe',
* policyId: 1n,
* }),
* ]
* })
* ```
*
* @param parameters - Client (optional), followed by the call arguments.
* @returns The call.
*/
function call(...parameters) {
const [client, args] = resolveCallParameters(parameters);
const { token, policyId } = args;
return defineCall({
address: resolveToken(client, { token }).address,
abi: Abis.tip20,
functionName: 'changeTransferPolicyId',
args: [policyId],
});
}
changeTransferPolicy.call = call;
/**
* Extracts the event from the logs.
*
* @param logs - Logs.
* @returns The event.
*/
function extractEvent(logs) {
const [log] = parseEventLogs({
abi: Abis.tip20,
logs,
eventName: 'TransferPolicyUpdate',
});
if (!log)
throw new Error('`TransferPolicyUpdate` event not found.');
return log;
}
changeTransferPolicy.extractEvent = extractEvent;
})(changeTransferPolicy || (changeTransferPolicy = {}));
/**
* Changes the transfer policy ID for a TIP20 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.token.changeTransferPolicySync(client, {
* token: '0x...',
* policyId: 1n,
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and event data.
*/
export async function changeTransferPolicySync(client, parameters) {
const { throwOnReceiptRevert = true, ...rest } = parameters;
const receipt = await changeTransferPolicy.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
});
const { args } = changeTransferPolicy.extractEvent(receipt.logs);
return {
...args,
receipt,
};
}
/**
* Creates a new TIP20 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.token.create(client, {
* name: 'My Token',
* symbol: 'MTK',
* currency: 'USD',
* logoURI: 'https://example.com/token.svg',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function create(client, parameters) {
return create.inner(writeContract, client, parameters);
}
(function (create) {
/** @internal */
async function inner(action, client, parameters) {
const { account = client.account, admin: admin_ = client.account, chain = client.chain, ...rest } = parameters;
const admin = admin_ ? parseAccount(admin_) : undefined;
if (!admin)
throw new Error('admin is required.');
const call = create.call(client, { ...rest, admin: admin.address });
return (await action(client, {
...parameters,
account,
chain,
...call,
}));
}
create.inner = inner;
/**
* Defines a call to the `createToken` 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.token.create.call(client, {
* name: 'My Token',
* symbol: 'MTK',
* currency: 'USD',
* logoURI: 'https://example.com/token.svg',
* admin: '0xfeed...fede',
* }),
* ]
* })
* ```
*
* @param parameters - Client (optional), followed by the call arguments.
* @returns The call.
*/
function call(...parameters) {
const [client, args] = resolveCallParameters(parameters);
const { name, symbol, currency, logoURI, quoteToken = Addresses.pathUsd, admin, salt = Hex.random(32), } = args;
return defineCall({
address: Addresses.tip20Factory,
abi: Abis.tip20Factory,
args: typeof logoURI === 'string'
? [
name,
symbol,
currency,
resolveToken(client, { token: quoteToken }).address,
admin,
salt,
logoURI,
]
: [
name,
symbol,
currency,
resolveToken(client, { token: quoteToken }).address,
admin,
salt,
],
functionName: 'createToken',
});
}
create.call = call;
/**
* Extracts the `TokenCreated` event from logs.
*
* @param logs - The logs.
* @returns The `TokenCreated` event.
*/
function extractEvent(logs) {
const [log] = parseEventLogs({
abi: Abis.tip20Factory,
logs,
eventName: 'TokenCreated',
strict: true,
});
if (!log)
throw new Error('`TokenCreated` event not found.');
return log;
}
create.extractEvent = extractEvent;
})(create || (create = {}));
/**
* Creates a new TIP20 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.token.createSync(client, {
* name: 'My Token',
* symbol: 'MTK',
* currency: 'USD',
* logoURI: 'https://example.com/token.svg',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and event data.
*/
export async function createSync(client, parameters) {
const { throwOnReceiptRevert = true, ...rest } = parameters;
const receipt = await create.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
});
const { args } = create.extractEvent(receipt.logs);
const tokenId = TokenId.fromAddress(args.token);
return {
...args,
receipt,
tokenId,
};
}
/**
* Gets TIP20 token allowance.
*
* @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 allowance = await Actions.token.getAllowance(client, {
* account: '0x...',
* spender: '0x...',
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The token allowance, in base units and human-readable form.
*/
export async function getAllowance(client, parameters) {
const { account, decimals, spender, token, ...rest } = parameters;
const [amount, { decimals: resolved }] = await Promise.all([
readContract(client, {
...rest,
...getAllowance.call(client, { account, spender, token }),
}),
resolveTokenWithDecimals(client, {
decimals,
token,
}),
]);
return internal_Token.toAmount(amount, resolved);
}
(function (getAllowance) {
/**
* Defines a call to the `allowance` function.
*
* Can be passed as a parameter to `multicall`, `simulateContract`, or any
* other action that accepts a contract call. The token is selected by `token`,
* which is either a TIP20 token id or a contract address.
*
* @param parameters - Client (optional), followed by the call arguments.
* @returns The call.
*/
function call(...parameters) {
const [client, args] = resolveCallParameters(parameters);
return defineCall({
address: resolveToken(client, args).address,
abi: Abis.tip20,
functionName: 'allowance',
args: [args.account, args.spender],
});
}
getAllowance.call = call;
})(getAllowance || (getAllowance = {}));
/**
* Gets TIP20 token balance for an 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 balance = await Actions.token.getBalance(client, {
* account: '0x...',
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The token balance, in base units and human-readable form.
*/
export async function getBalance(client, parameters) {
const { account: account_ = client.account, decimals, token, ...rest } = parameters;
if (!account_)
throw new AccountNotFoundError();
const account = parseAccount(account_).address;
const [amount, { decimals: resolved }] = await Promise.all([
readContract(client, {
...rest,
...getBalance.call(client, { account, token }),
}),
resolveTokenWithDecimals(client, {
decimals,
token,
}),
]);
return internal_Token.toAmount(amount, resolved);
}
(function (getBalance) {
/**
* Defines a call to the `balanceOf` function.
*
* Can be passed as a parameter to `multicall`, `simulateContract`, or any
* other action that accepts a contract call. The token is selected by `token`,
* which is either a TIP20 token id or a contract address.
*
* @param parameters - Client (optional), followed by the call arguments.
* @returns The call.
*/
function call(...parameters) {
const [client, args] = resolveCallParameters(parameters);
const account_ = args.account ?? client?.account;
if (!account_)
throw new AccountNotFoundError();
const account = parseAccount(account_).address;
return defineCall({
address: resolveToken(client, args).address,
abi: Abis.tip20,
functionName: 'balanceOf',
args: [account],
});
}
getBalance.call = call;
})(getBalance || (getBalance = {}));
/**
* Gets TIP20 token metadata including name, symbol, logo URI, currency, decimals, and total supply.
*
* @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 metadata = await Actions.token.getMetadata(client, {
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The token metadata.
*/
export async function getMetadata(client, parameters) {
const { token, ...rest } = parameters;
const { address } = resolveToken(client, { token });
const abi = Abis.tip20;
const declared = findDeclaredToken(client, token);
const overrides = {
...(declared?.decimals != null ? { decimals: declared.decimals } : {}),
...(declared?.name != null ? { name: declared.name } : {}),
...(declared?.symbol != null ? { symbol: declared.symbol } : {}),
};
if (TokenId.fromAddress(address) === TokenId.fromAddress(Addresses.pathUsd))
return multicall(client, {
...rest,
contracts: [
{
address,
abi,
functionName: 'currency',
},
{
address,
abi,
functionName: 'decimals',
},
{
address,
abi,
functionName: 'logoURI',
},
{
address,
abi,
functionName: 'name',
},
{
address,
abi,
functionName: 'symbol',
},
{
address,
abi,
functionName: 'totalSupply',
},
],
allowFailure: true,
deployless: true,
}).then(([currency, decimals, logoURI, name, symbol, totalSupply]) => ({
name: unwrapMulticallResult(name),
symbol: unwrapMulticallResult(symbol),
currency: unwrapMulticallResult(currency),
decimals: unwrapMulticallResult(decimals),
logoURI: unwrapMulticallResult(logoURI, ''),
totalSupply: unwrapMulticallResult(totalSupply),
...overrides,
}));
return multicall(client, {
...rest,
contracts: [
{
address,
abi,
functionName: 'currency',
},
{
address,
abi,
functionName: 'decimals',
},
{
address,
abi,
functionName: 'logoURI',
},
{
address,
abi,
functionName: 'quoteToken',
},
{
address,
abi,
functionName: 'name',
},
{
address,
abi,
functionName: 'paused',
},
{
address,
abi,
functionName: 'supplyCap',
},
{
address,
abi,
functionName: 'symbol',
},
{
address,
abi,
functionName: 'totalSupply',
},
{
address,
abi,
functionName: 'transferPolicyId',
},
],
allowFailure: true,
deployless: true,
}).then(([currency, decimals, logoURI, quoteToken, name, paused, supplyCap, symbol, totalSupply, transferPolicyId,]) => ({
name: unwrapMulticallResult(name),
symbol: unwrapMulticallResult(symbol),
currency: unwrapMulticallResult(currency),
decimals: unwrapMulticallResult(decimals),
logoURI: unwrapMulticallResult(logoURI, ''),
quoteToken: unwrapMulticallResult(quoteToken),
totalSupply: unwrapMulticallResult(totalSupply),
paused: unwrapMulticallResult(paused),
supplyCap: unwrapMulticallResult(supplyCap),
transferPolicyId: unwrapMulticallResult(transferPolicyId),
...overrides,
}));
}
function unwrapMulticallResult(response, ...fallback) {
if (response.status === 'failure') {
if (fallback.length > 0)
return fallback[0];
throw response.error;
}
return response.result;
}
/**
* Gets the total supply of a TIP20 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 totalSupply = await Actions.token.getTotalSupply(client, {
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The token total supply, in base units and human-readable form.
*/
export async function getTotalSupply(client, parameters) {
const { decimals, token, ...rest } = parameters;
const [amount, { decimals: resolved }] = await Promise.all([
readContract(client, {
...rest,
...getTotalSupply.call(client, { token }),
}),
resolveTokenWithDecimals(client, {
decimals,
token,
}),
]);
return internal_Token.toAmount(amount, resolved);
}
(function (getTotalSupply) {
/**
* Defines a call to the `totalSupply` function.
*
* Can be passed as a parameter to `multicall`, `simulateContract`, or any
* other action that accepts a contract call. The token is selected by `token`,
* which is either a TIP20 token id or a contract address.
*
* @param parameters - Client (optional), followed by the call arguments.
* @returns The call.
*/
function call(...parameters) {
const [client, args] = resolveCallParameters(parameters);
return defineCall({
address: resolveToken(client, args).address,
abi: Abis.tip20,
args: [],
functionName: 'totalSupply',
});
}
getTotalSupply.call = call;
})(getTotalSupply || (getTotalSupply = {}));
/**
* Gets the admin role for a specific role in a TIP20 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 adminRole = await Actions.token.getRoleAdmin(client, {
* role: 'issuer',
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The admin role hash.
*/
export async function getRoleAdmin(client, parameters) {
return readContract(client, {
...parameters,
...getRoleAdmin.call(client, parameters),
});
}
(function (getRoleAdmin) {
/**
* Defines a call to the `getRoleAdmin` function.
*
* @param parameters - Client (optional), followed by the call arguments.
* @returns The call.
*/
function call(...parameters) {
const [client, args] = resolveCallParameters(parameters);
const { role, token } = args;
return defineCall({
address: resolveToken(client, { token }).address,
abi: Abis.tip20,
functionName: 'getRoleAdmin',
args: [TokenRole.serialize(role)],
});
}
getRoleAdmin.call = call;
})(getRoleAdmin || (getRoleAdmin = {}));
/**
* Checks if an account has a specific role for a TIP20 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 hasRole = await Actions.token.hasRole(client, {
* account: '0x...',
* role: 'issuer',
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns Whether the account has the role.
*/
export async function hasRole(client, parameters) {
const { account = client.account } = parameters;
const address = account ? parseAccount(account).address : undefined;
if (!address)
throw new Error('account is required.');
return readContract(client, {
...parameters,
...hasRole.call(client, { ...parameters, account: address }),
});
}
(function (hasRole) {
/**
* Defines a call to the `hasRole` function.
*
* @param parameters - Client (optional), followed by the call arguments.
* @returns The call.
*/
function call(...parameters) {
const [client, args] = resolveCallParameters(parameters);
const { account, role, token } = args;
return defineCall({
address: resolveToken(client, { token }).address,
abi: Abis.tip20,
functionName: 'hasRole',
args: [account, TokenRole.serialize(role)],
});
}
hasRole.call = call;
})(hasRole || (hasRole = {}));
/**
* Grants a role for a TIP20 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.token.grantRoles(client, {
* token: '0x...',
* to: '0x...',
* roles: ['issuer'],
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function grantRoles(client, parameters) {
return grantRoles.inner(sendTransaction, client, parameters);
}
(function (grantRoles) {
/** @internal */
async function inner(action, client, parameters) {
return (await action(client, {
...parameters,
calls: parameters.roles.map((role) => {
const call = grantRoles.call(client, { ...parameters, role });
return {
...call,
data: encodeFunctionData(call),
};
}),
}));
}
grantRoles.inner = inner;
/**
* Defines a call to the `grantRole` 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.token.grantRoles.call(client, {
* token: '0x20c0...babe',
* to: '0x20c0...beef',
* role: 'issuer',
* }),
* ]
* })
* ```
*
* @param parameters - Client (optional), followed by the call arguments.
* @returns The call.
*/
function call(...parameters) {
const [client, args] = resolveCallParameters(parameters);
const { token, to, role } = args;
const roleHash = TokenRole.serialize(role);
return defineCall({
address: resolveToken(client, { token }).address,
abi: Abis.tip20,
functionName: 'grantRole',
args: [roleHash, to],
});
}
grantRoles.call = call;
/**
* Extracts the events from the logs.
*
* @param logs - Logs.
* @returns The events.
*/
function extractEvents(logs) {
const events = parseEventLogs({
abi: Abis.tip20,
logs,
eventName: 'RoleMembershipUpdated',
});
if (events.length === 0)
throw new Error('`RoleMembershipUpdated` events not found.');
return events;
}
grantRoles.extractEvents = extractEvents;
})(grantRoles || (grantRoles = {}));
/**
* Grants a role for a TIP20 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.token.grantRolesSync(client, {
* token: '0x...',
* to: '0x...',
* roles: ['issuer'],
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and event data.
*/
export async function grantRolesSync(client, parameters) {
const { throwOnReceiptRevert = true, ...rest } = parameters;
const receipt = await grantRoles.inner(sendTransactionSync, client, {
...rest,
throwOnReceiptRevert,
});
const events = grantRoles.extractEvents(receipt.logs);
const value = events.map((event) => event.args);
return {
receipt,
value,
};
}
/**
* Mints TIP20 tokens to an 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 result = await Actions.token.mint(client, {
* to: '0x...',
* amount: 100n,
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function mint(client, parameters) {
return mint.inner(writeContract, client, parameters);
}
(function (mint) {
/** @internal */
async function inner(action, client, parameters) {
const { amount, memo, to, token, ...rest } = parameters;
const call = mint.call(client, { amount, memo, to, token });
return (await action(client, {
...rest,
...call,
}));
}
mint.inner = inner;
/**
* Defines a call to the `mint` or `mintWithMemo` 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.token.mint.call(client, {
* to: '0x20c0...beef',
* amount: 100n,
* token: '0x20c0...babe',
* }),
* ]
* })
* ```
*
* `amount.decimals` is inferred from the client's declared `tokens` when omitted.
*
* @param parameters - Client (optional), followed by the call arguments.
* @returns The call.
*/
function call(...parameters) {
const [client, args] = resolveCallParameters(parameters);
const { to, amount, memo, token } = args;
const { address, decimals } = resolveToken(client, { token });
const value = internal_Token.toBaseUnits(amount, decimals);
const callArgs = memo
? {
functionName: 'mintWithMemo',
args: [to, value, Hex.padLeft(memo, 32)],
}
: {
functionName: 'mint',
args: [to, value],
};
return defineCall({
address,
abi: Abis.tip20,
...callArgs,
});
}
mint.call = call;
/**
* Extracts the event from the logs.
*
* @param logs - Logs.
* @returns The event.
*/
function extractEvent(logs) {
const [log] = parseEventLogs({
abi: Abis.tip20,
logs,
eventName: 'Mint',
});
if (!log)
throw new Error('`Mint` event not found.');
return log;
}
mint.extractEvent = extractEvent;
})(mint || (mint = {}));
/**
* Mints TIP20 tokens to an 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 result = await Actions.token.mintSync(client, {
* to: '0x...',
* amount: 100n,
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction receipt and event data.
*/
export async function mintSync(client, parameters) {
const { throwOnReceiptRevert = true, ...rest } = parameters;
const receipt = await mint.inner(writeContractSync, client, {
...rest,
throwOnReceiptRevert,
});
const { args } = mint.extractEvent(receipt.logs);
return {
...args,
receipt,
};
}
/**
* Pauses a TIP20 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.token.pause(client, {
* token: '0x...',
* })
* ```
*
* @param client - Client.
* @param parameters - Parameters.
* @returns The transaction hash.
*/
export async function pause(client, parameters) {
return pause.inner(writeContract, client, parameters);
}
(function (pause) {
/** @internal */
async function inner(action, client, parameters) {
const { token, ...rest } = parameters;
const call = pause.call(client, { token });
return (await action(client, {
...rest,
...call,
}));
}
pause.inner = inner;
/**
* Defines a call to the `pause` 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'
* i