UNPKG

@fotonjs/core

Version:
361 lines (330 loc) 17.9 kB
import { Transaction, RpcClient, CreateClientOptions } from '@fotonjs/api'; import { TonConnectError, WalletInfo, Wallet, TonConnect, TonConnectOptions } from '@tonconnect/sdk'; export { Wallet, WalletInfo } from '@tonconnect/sdk'; import { TonConnectUIError as TonConnectUIError$1, TonConnectUI, TonConnectUiOptionsWithManifest } from '@tonconnect/ui'; import { Contract, Address, Cell, toNano } from '@ton/core'; interface WaitForTransactionOptions { hash: string; refetchInterval?: number; refetchLimit?: number; } declare function waitForTransaction(this: PublicClient, options: WaitForTransactionOptions): Promise<Transaction | undefined>; interface GetBalanceOptions { address: string; } declare function getBalance(this: PublicClient, options: GetBalanceOptions): Promise<bigint | undefined>; interface PublicClient { _api: RpcClient; waitForTransaction: typeof waitForTransaction; getBalance: typeof getBalance; } type CreatePublicClientOptions = CreateClientOptions; declare const createPublicClient: (options?: CreateClientOptions) => PublicClient; type Chain = 'mainnet' | 'testnet'; declare class UserError extends Error { constructor(message: string); } declare class UserUnauthorizedError extends UserError { constructor(); } declare class UserRejectedConnectionError extends UserError { constructor(); } declare class UserRejectedTransactionError extends UserError { constructor(); } declare class SyntaxError extends Error { constructor(message: string); } declare class ConnectFunctionUnavailableError extends SyntaxError { constructor(); } declare class ConnectUIFunctionUnavailableError extends SyntaxError { constructor(); } declare class ConnectUIFunctionUnavailableInNodeError extends SyntaxError { constructor(); } declare class ReconnectFunctionUnavailableError extends SyntaxError { constructor(); } declare class IncorrectContractError extends SyntaxError { constructor(); } declare class MissingContractAddressError extends SyntaxError { constructor(); } declare class TonConnectUIError extends TonConnectError { constructor(...args: ConstructorParameters<typeof Error>); } declare class TonError extends Error { constructor(message: string); } declare class TonWalletConnectionError extends TonError { constructor(); } declare class TonWalletDisconnectError extends TonError { constructor(); } declare class TonReadError extends TonError { constructor(); } declare class TonRateLimitError extends TonError { constructor(); } type SupportedErrors = { ConnectFunctionUnavailableError: ConnectFunctionUnavailableError; ConnectUIFunctionUnavailableError: ConnectUIFunctionUnavailableError; ConnectUIFunctionUnavailableInNodeError: ConnectUIFunctionUnavailableInNodeError; ReconnectFunctionUnavailableError: ReconnectFunctionUnavailableError; IncorrectContractError: IncorrectContractError; MissingContractAddressError: MissingContractAddressError; UserUnauthorizedError: UserUnauthorizedError; UserRejectedConnectionError: UserRejectedConnectionError; UserRejectedTransactionError: UserRejectedTransactionError; TonConnectError: TonConnectError; TonConnectUIError: TonConnectUIError; TonWalletConnectionError: TonWalletConnectionError; TonWalletDisconnectError: TonWalletDisconnectError; TonReadError: TonReadError; TonRateLimitError: TonRateLimitError; }; /** The main type to be returned from the functions. Returns either data or error */ type DataOrError<DATA, ERROR extends Error = Error> = { data: DATA; error: undefined; } | { data: undefined; error: ERROR; }; type ValuesType<T> = T[keyof T]; type PickErrors<KEYS extends keyof SupportedErrors> = ValuesType<Pick<SupportedErrors, KEYS>>; /** * An utility type that must be used for the core functions of Foton. * * For example, a function can have the following signature: * ``` * type SendTransaction = (options) => Promise<DataOrTypedError<string, 'UserUnauthorizedError'>> * ``` * * This would mean that the function can return either a string or the UserUnauthorizedError. */ type DataOrTypedError<DATA, ERROR_KEYS extends keyof SupportedErrors> = DataOrError<DATA, PickErrors<ERROR_KEYS>>; type WalletFilterType = 'all' | 'injected' | 'injectable' | 'remote' | 'embedded'; interface GetWalletsOptions { type?: WalletFilterType; } declare function getWallets(this: WalletClientBase, options?: GetWalletsOptions): Promise<DataOrError<WalletInfo[]>>; type ConnectReturn = DataOrTypedError<Wallet, 'ConnectFunctionUnavailableError' | 'TonConnectUIError' | 'TonWalletConnectionError' | 'UserRejectedConnectionError'>; declare function connect(this: WalletClientBase, connector: WalletInfo): Promise<ConnectReturn>; type ConnectUiReturn = DataOrTypedError<Wallet, 'ConnectUIFunctionUnavailableError' | 'TonConnectUIError' | 'TonWalletConnectionError' | 'UserRejectedConnectionError'>; declare function connectUI(this: WalletClientBase, connector?: WalletInfo): Promise<ConnectUiReturn>; type ReconnectReturn = DataOrTypedError<Wallet, 'ReconnectFunctionUnavailableError' | 'TonWalletConnectionError' | 'TonConnectError' | 'TonConnectUIError'>; declare function reconnect(this: WalletClient): Promise<ReconnectReturn>; type DisconnectReturn = DataOrTypedError<boolean, 'TonWalletDisconnectError' | 'TonConnectError'>; declare function disconnect(this: WalletClientBase): Promise<DisconnectReturn>; interface SendTransactionOptions { to: string; value: bigint; } declare function sendTransaction(this: WalletClientBase, options: SendTransactionOptions): Promise<DataOrTypedError<string, 'UserUnauthorizedError' | 'UserRejectedTransactionError'>>; interface WalletClientBase { _chain: Chain; _wallet: Wallet | undefined; _connectionCallbacks: ((wallet: TonConnectError | TonConnectUIError$1 | Wallet | null) => void)[]; address?: string; connected: boolean; connection: TonConnect | TonConnectUI; wallets?: WalletInfo[]; getWallets: typeof getWallets; disconnect: typeof disconnect; sendTransaction: typeof sendTransaction; } interface WalletClient extends WalletClientBase { connect: typeof connect; reconnect: typeof reconnect; } interface WalletClientUI extends WalletClientBase { connect: typeof connectUI; } interface CreateWalletClientOptionsBase { chain?: Chain; } interface CreateWalletClientOptionsWithTC extends CreateWalletClientOptionsBase { connection: TonConnect; manifestUrl?: never; } interface CreateWalletClientOptionsFull$1 extends TonConnectOptions, CreateWalletClientOptionsBase { connection?: never; } type CreateWalletClientOptions = CreateWalletClientOptionsFull$1 | CreateWalletClientOptionsWithTC; declare function createWalletClient(options?: CreateWalletClientOptions): WalletClient; interface CreateWalletClientUIOptionsBase { chain?: Chain; } interface CreateWalletClientUIOptionsWithTC extends CreateWalletClientUIOptionsBase { connection: TonConnectUI; manifestUrl?: never; } interface CreateWalletClientOptionsFull extends TonConnectUiOptionsWithManifest, CreateWalletClientUIOptionsBase { connection?: never; } type CreateWalletClientUIOptions = CreateWalletClientOptionsFull | CreateWalletClientUIOptionsWithTC; declare function createWalletClientUI(options?: CreateWalletClientUIOptions): WalletClientUI; interface ContractMethodMessage extends Record<string, unknown> { $$type: string; } type ContractMethodArgs = ContractMethodMessage | string | null; interface ExtendedContract extends Contract { send(arg_0: unknown, arg_1: unknown, arg_2: unknown, message: ContractMethodArgs): Promise<void>; } interface CompiledContract { fromInit(...args: any): Promise<ExtendedContract>; fromAddress(address: Address): ExtendedContract; } type GetExtendedContract<CONTRACT extends CompiledContract> = CONTRACT extends { fromInit(...args: any): Promise<infer T>; } ? T : never; type MapMethodPayload<T> = { [K in keyof T]: T[K] extends Address ? string : T[K]; }; /** * Takes a contract and returns a union-type of the method arguments that a contract can run. * * For example, given contract (in Tact) has only one receiver `receive(msg: Add)`, then the contract has methods `Add | Deploy`, * and the type will be `{ $$type: 'Add', amount: bigint } | { $$type: 'Deploy', queryId: bigint }`. */ type ContractMethods<CONTRACT extends CompiledContract> = Parameters<GetExtendedContract<CONTRACT>['send']>[3]; type ContractMethodNamesKeyed<CONTRACT extends CompiledContract> = Extract<ContractMethods<CONTRACT>, string> extends string ? Extract<ContractMethods<CONTRACT>, string> : never; type ContractMethodNamesEmpty<CONTRACT extends CompiledContract> = Extract<ContractMethods<CONTRACT>, null> extends null ? 'empty' : never; type ContractMethodNamesMessage<CONTRACT extends CompiledContract> = Exclude<// add support for receive(msg: MSG) Exclude<ContractMethods<CONTRACT>, string | null> extends ContractMethodMessage ? Exclude<ContractMethods<CONTRACT>, string | null>['$$type'] : ContractMethods<CONTRACT> extends null ? 'empty' : ContractMethods<CONTRACT> extends string ? ContractMethods<CONTRACT> : string, 'Deploy'>; /** * Takes a contract and returns a union-type of the available method names, without deploy method. * * For example, given contract (in Tact) has two receivers `receive(msg: Add)` and `receive(msg: Subtract)`, * then the type will be `'Add' | 'Subtract'`. * * Different contract receivers all map to a string method name. Here is the mapping: * 1. `receive(msg: Add)` -> `'Add'` * 2. `receive("increment")` -> `'increment'` * 3. `receive(str: String)` -> `string`, any string method name is allowed * 4. `receive()` -> `'empty'`, requires passing 'empty' explicitly */ type ContractMethodNames<CONTRACT extends CompiledContract> = ContractMethodNamesMessage<CONTRACT> | ContractMethodNamesKeyed<CONTRACT> | ContractMethodNamesEmpty<CONTRACT>; /** * Takes a contract and a key of the method, and returns the method's arguments. * * For example, given contract (in Tact) has only one receiver `receive(msg: Add)`, * then running `ContractMethod<Contract, 'Add'>` will return `{ amount: bigint }`. */ type ContractMethod<CONTRACT extends CompiledContract, KEY extends string> = Exclude<ContractMethods<CONTRACT>, string | null> extends { $$type: infer TYPE; } ? TYPE extends KEY ? MapMethodPayload<Omit<Extract<ContractMethods<CONTRACT>, { $$type: TYPE; }>, '$$type'>> : undefined : undefined; /** * Takes a contract and return an array of the required arguments for the deploy method. * * For example, given contract (in Tact) has a constructor defined as `init(id: Int, count: Int)`, * then the type will be `[arg0: bigint, arg1: bigint]`. */ type ContractDeployArguments<CONTRACT extends CompiledContract> = Parameters<CONTRACT['fromInit']>; type WithoutFirst<T extends any[]> = T extends [any, ...infer Rest] ? Rest : never; type SnakeCaseHelper<S extends string> = S extends `${infer First}${infer Rest}` ? `${First extends Capitalize<First> ? `_${Lowercase<First>}` : First}${SnakeCaseHelper<Rest>}` : S; type SnakeCase<S extends string> = S extends `${infer First}${infer Rest}` ? `${Lowercase<First>}${SnakeCaseHelper<Rest>}` : S; type CamelCase<S extends string> = S extends `${infer First}_${infer Next}${infer Rest}` ? `${First}${Capitalize<Next>}${CamelCase<Rest>}` : S; type ExtractGetterNames<CONTRACT extends CompiledContract> = Exclude<{ [K in keyof GetExtendedContract<CONTRACT>]: GetExtendedContract<CONTRACT>[K] extends Function ? K extends `get${string}` ? K : never : never; }[keyof GetExtendedContract<CONTRACT>], undefined>; type CapitalizeGetter<GETTER extends string> = `get${Capitalize<GETTER>}`; type GetCapitalizedGetter<GETTER extends string, CONTRACT extends ExtendedContract> = CapitalizeGetter<GETTER> extends keyof CONTRACT ? CONTRACT[CapitalizeGetter<GETTER>] : never; /** * Takes a contract and returns a union-type of the getter names. * Contract getters request data from the contract without modifying it. * * For example, given contract (in Tact) has two getters `get fun balance` and `get fun counter`, * then the type will be `balance | counter`. */ type ContractGetterNames<CONTRACT extends CompiledContract> = ExtractGetterNames<CONTRACT> extends `get${infer REST}` ? SnakeCase<REST> | Uncapitalize<REST> : never; /** * Takes a contract and returns a record of the getter names and their arguments. * Contract getters request data from the contract without modifying it. * * For example, given contract (in Tact) has two getters `get fun balance(initial: Int): Int` and `get fun counter(): Int`, * then the type will be `{ balance: [bigint], counter: [] }`. */ type ContractGetters<CONTRACT extends CompiledContract> = { [key in CamelCase<ContractGetterNames<CONTRACT>>]: GetCapitalizedGetter<key, GetExtendedContract<CONTRACT>> extends (...args: any) => any ? WithoutFirst<Parameters<GetCapitalizedGetter<key, GetExtendedContract<CONTRACT>>>> : never; }; type UnwrapPromise<T> = T extends Promise<infer U> ? U : T; type MapGetterReturn<T> = T extends bigint ? number : T extends Address ? string : T; /** * Takes a contract with a getter name, and gets the return type of the getter. * * For example, for a contract (in Tact) with a getter `get fun balance(initial: Int): Int`, * the type will be `bigint`. */ type ContractGetterReturn<CONTRACT extends CompiledContract, GETTER extends ContractGetterNames<CONTRACT>> = GetCapitalizedGetter<GETTER, GetExtendedContract<CONTRACT>> extends (...args: any) => any ? MapGetterReturn<UnwrapPromise<ReturnType<GetCapitalizedGetter<GETTER, GetExtendedContract<CONTRACT>>>>> : unknown; interface WriteContractOptions<CONTRACT extends CompiledContract, METHOD extends ContractMethodNames<CONTRACT>> { value: bigint; method: METHOD; payload: ContractMethod<CONTRACT, METHOD>; } type WriteContractReturn = DataOrTypedError<string, 'MissingContractAddressError' | 'UserUnauthorizedError' | 'IncorrectContractError' | 'UserRejectedTransactionError'>; declare function writeContract<CONTRACT extends CompiledContract, METHOD extends ContractMethodNames<CONTRACT>>(this: ContractClient<CONTRACT>, options: WriteContractOptions<CONTRACT, METHOD>): Promise<WriteContractReturn>; interface ReadContractOptions<CONTRACT extends CompiledContract, GETTER extends ContractGetterNames<CONTRACT>> { getter: GETTER; arguments: ContractGetters<CONTRACT>[CamelCase<GETTER>]; } type ReadContractReturn<CONTRACT extends CompiledContract, GETTER extends ContractGetterNames<CONTRACT>> = DataOrTypedError<ContractGetterReturn<CONTRACT, GETTER> | undefined, 'MissingContractAddressError' | 'IncorrectContractError' | 'TonReadError' | 'TonRateLimitError'>; declare function readContract<CONTRACT extends CompiledContract, GETTER extends ContractGetterNames<CONTRACT>>(this: ContractClient<CONTRACT>, options: ReadContractOptions<CONTRACT, GETTER>): Promise<ReadContractReturn<CONTRACT, GETTER>>; declare function setAddress<CONTRACT extends CompiledContract>(this: ContractClient<CONTRACT>, address: string | undefined): void; interface CreateContractClientOptions<CONTRACT extends CompiledContract> { publicClient: PublicClient; walletClient: WalletClientBase; contract: CONTRACT; address?: string; } interface ContractClient<CONTRACT extends CompiledContract> { _publicClient: PublicClient; _walletClient: WalletClientBase; _contract: CONTRACT; address?: string; setAddress: typeof setAddress; deploy: typeof deployContract; write: typeof writeContract; read: typeof readContract; } interface DeployContractOptions<CONTRACT extends CompiledContract> { value: bigint; arguments: ContractDeployArguments<CONTRACT>; payload: ContractMethod<CONTRACT, 'Deploy'>; } interface DeployContractData { address: string; txHash: string; } type DeployContractReturn = DataOrTypedError<DeployContractData, 'UserUnauthorizedError' | 'IncorrectContractError' | 'UserRejectedTransactionError'>; declare function deployContract<CONTRACT extends CompiledContract>(this: ContractClient<CONTRACT>, options: DeployContractOptions<CONTRACT>): Promise<DeployContractReturn>; declare const createContractClient: <CONTRACT extends CompiledContract>(options: CreateContractClientOptions<CONTRACT>) => ContractClient<CONTRACT>; interface JettonMetadata { name: string; description: string; symbol: string; image: string; imageData: string; uri: string; amount_style: 'n' | 'n-of-total' | '%'; render_type: 'currency' | 'game'; } interface GetJettonDeployArgumentsOptions { owner: string; content: Partial<JettonMetadata>; maxSupply: bigint; } type GetJettonDeployArgumentsReturn = [owner: Address, content: Cell, max_supply: bigint]; declare const getJettonDeployArguments: (options: GetJettonDeployArgumentsOptions) => GetJettonDeployArgumentsReturn; declare const parseTon: typeof toNano; declare const composePayload: (contract: Contract, method: "empty" | string, payload?: Record<string, unknown>) => string | undefined; export { type CompiledContract, type ContractClient, type ContractDeployArguments, type ContractGetterNames, type ContractGetterReturn, type ContractMethod, type ContractMethodNames, type ContractMethods, type CreateContractClientOptions, type CreatePublicClientOptions, type CreateWalletClientOptions, type CreateWalletClientUIOptions, type DeployContractOptions, type ExtendedContract, type GetWalletsOptions, type PublicClient, type SendTransactionOptions, type WalletClient, type WalletClientBase, type WalletClientUI, composePayload, createContractClient, createPublicClient, createWalletClient, createWalletClientUI, getJettonDeployArguments, parseTon };