From d235e7fc964b0d06fcd7960dddf6fe515b511fa1 Mon Sep 17 00:00:00 2001 From: VK Date: Thu, 14 May 2026 14:30:04 +0400 Subject: [PATCH 1/2] docs: reference generator and generated artifacts Squash of all documentation work from docs/codegen on top of the code branch: docs-generator tooling (reference-generator, template-resolver), JSDoc additions and improvements across source files, examples sources, generated reference.md files, docs/templates mirror, in-source README files, package READMEs, the document-public-api skill, and removal of legacy template/ tree. --- .claude/skills/add-action-and-hook/SKILL.md | 34 +- .claude/skills/add-ui-component/SKILL.md | 10 + .claude/skills/document-public-api/SKILL.md | 224 + {demo => docs}/examples/.gitignore | 0 {demo => docs}/examples/env.d.ts | 0 {demo => docs}/examples/index.html | 0 {demo => docs}/examples/package.json | 0 .../examples/src/__mocks__/@ton/walletkit.ts | 0 .../examples/src/__mocks__/@tonconnect/sdk.ts | 0 .../src/__mocks__/@tonconnect/ui-react.ts | 0 .../examples/src/__tests__/initialize.test.ts | 0 .../examples/src/__tests__/jettons.test.ts | 0 .../examples/src/__tests__/requests.test.ts | 0 .../examples/src/__tests__/setup.ts | 0 .../examples/src/__tests__/test-utils.tsx | 0 .../examples/src/__tests__/transfers.test.ts | 0 .../src/__tests__/ui-state-wiring.test.ts | 0 .../examples/src/__tests__/ui.test.ts | 0 .../wallet-kit-initialize-sample.test.ts | 0 .../appkit/actions/balances/balances.test.ts | 7 +- .../balances/get-balance-by-address.ts | 4 +- .../appkit/actions/balances/get-balance.ts | 2 +- .../balances/watch-balance-by-address.ts | 0 .../appkit/actions/balances/watch-balance.ts | 0 .../actions/connectors/add-connector.ts | 6 +- .../src/appkit/actions/connectors/connect.ts | 0 .../actions/connectors/connectors.test.ts | 16 +- .../appkit/actions/connectors/disconnect.ts | 0 .../actions/connectors/get-connector-by-id.ts | 0 .../actions/connectors/get-connectors.ts | 0 .../connectors/watch-connector-by-id.ts | 0 .../actions/connectors/watch-connectors.ts | 0 .../create-transfer-jetton-transaction.ts | 0 .../actions/jettons/get-jetton-balance.ts | 2 +- .../appkit/actions/jettons/get-jetton-info.ts | 0 .../jettons/get-jetton-wallet-address.ts | 0 .../actions/jettons/get-jettons-by-address.ts | 2 +- .../src/appkit/actions/jettons/get-jettons.ts | 2 +- .../appkit/actions/jettons/jettons.test.ts | 5 +- .../appkit/actions/jettons/transfer-jetton.ts | 0 .../appkit/actions/network/get-api-client.ts | 0 .../actions/network/get-block-number.ts | 0 .../actions/network/get-default-network.ts | 0 .../src/appkit/actions/network/get-network.ts | 0 .../appkit/actions/network/get-networks.ts | 0 .../actions/network/has-streaming-provider.ts | 0 .../appkit/actions/network/network.test.ts | 0 .../actions/network/set-default-network.ts | 0 .../actions/network/watch-default-network.ts | 0 .../appkit/actions/network/watch-networks.ts | 0 .../nft/create-transfer-nft-transaction.ts | 0 .../src/appkit/actions/nft/get-nft.ts | 0 .../appkit/actions/nft/get-nfts-by-address.ts | 2 +- .../src/appkit/actions/nft/get-nfts.ts | 0 .../src/appkit/actions/nft/nfts.test.ts | 0 .../src/appkit/actions/nft/transfer-nft.ts | 0 .../appkit/actions/onramp/build-onramp-url.ts | 0 .../onramp/get-crypto-onramp-provider.ts | 0 .../onramp/get-crypto-onramp-providers.ts | 0 .../appkit/actions/onramp/get-onramp-quote.ts | 0 .../actions/providers/register-provider.ts | 0 .../src/appkit/actions/signing/sign-binary.ts | 0 .../src/appkit/actions/signing/sign-cell.ts | 2 +- .../src/appkit/actions/signing/sign-text.ts | 0 .../appkit/actions/signing/signing.test.ts | 0 .../appkit/actions/staking/staking-actions.ts | 2 +- .../appkit/actions/staking/staking.test.ts | 0 .../src/appkit/actions/swap/swap-actions.ts | 0 .../src/appkit/actions/swap/swap.test.ts | 0 .../create-transfer-ton-transaction.ts | 2 +- .../actions/transaction/send-transaction.ts | 0 .../actions/transaction/transaction.test.ts | 0 .../actions/transaction/transfer-ton.ts | 0 .../actions/wallets/get-connected-wallets.ts | 0 .../actions/wallets/get-selected-wallet.ts | 0 .../actions/wallets/set-selected-wallet-id.ts | 0 .../appkit/actions/wallets/wallets.test.ts | 0 .../wallets/watch-connected-wallets.ts | 0 .../actions/wallets/watch-selected-wallet.ts | 0 .../components/balances/balances.test.tsx | 0 .../balances/send-jetton-button.tsx | 0 .../components/balances/send-ton-button.tsx | 0 .../crypto-onramp/crypto-onramp-widget.tsx | 17 + .../crypto-onramp/crypto-onramp.test.tsx | 55 + .../src/appkit/components/nfts/nft-item.tsx | 24 + .../src/appkit/components/nfts/nfts.test.tsx | 37 + .../components/providers/app-kit-provider.tsx | 2 +- .../components/providers/i18n-provider.tsx | 21 + .../components/providers/providers.test.tsx | 21 + .../components/shared/amount-presets.tsx | 29 + .../appkit/components/shared/copy-button.tsx | 15 + .../components/shared/currency-item.tsx | 28 + .../components/shared/low-balance-modal.tsx | 30 + .../components/shared/option-switcher.tsx | 24 + .../components/shared/settings-button.tsx | 17 + .../appkit/components/shared/shared.test.tsx | 82 + .../components/shared/token-select-modal.tsx | 53 + .../components/shared/token-selector.tsx | 24 + .../staking/select-unstake-mode.tsx | 33 + .../staking/staking-balance-block.tsx | 34 + .../staking/staking-settings-modal.tsx | 35 + .../components/staking/staking-widget.tsx | 17 + .../components/staking/staking.test.tsx | 69 + .../src/appkit/components/swap/swap-field.tsx | 41 + .../components/swap/swap-flip-button.tsx | 18 + .../src/appkit/components/swap/swap-info.tsx | 29 + .../appkit/components/swap/swap-widget.tsx | 38 + .../src/appkit/components/swap/swap.test.tsx | 75 + .../transaction/transaction.test.tsx | 0 .../components/transaction/transaction.tsx | 0 .../src/appkit/components/ui/block.tsx | 20 + .../src/appkit/components/ui/button.tsx | 21 + .../components/ui/centered-amount-input.tsx | 17 + .../src/appkit/components/ui/collapsible.tsx | 24 + .../src/appkit/components/ui/info-block.tsx | 26 + .../src/appkit/components/ui/input.tsx | 27 + .../components/ui/logo-with-network.tsx | 24 + .../src/appkit/components/ui/logo.tsx | 15 + .../src/appkit/components/ui/modal.tsx | 24 + .../src/appkit/components/ui/select.tsx | 25 + .../src/appkit/components/ui/skeleton.tsx | 15 + .../src/appkit/components/ui/tabs.tsx | 30 + .../src/appkit/components/ui/ui.test.tsx | 104 + .../components/wallets/connect-button.tsx | 0 .../appkit/connectors/tonconnect/connector.ts | 0 .../appkit/hooks/balances/balances.test.tsx | 0 .../hooks/balances/use-balance-by-address.tsx | 2 +- .../src/appkit/hooks/balances/use-balance.tsx | 2 +- .../balances/use-watch-balance-by-address.tsx | 0 .../hooks/balances/use-watch-balance.tsx | 0 .../appkit/hooks/core/use-app-kit-theme.tsx | 0 .../src/appkit/hooks/core/use-app-kit.tsx | 0 .../src/appkit/hooks/jettons/jettons.test.tsx | 0 .../jettons/use-jetton-balance-by-address.tsx | 0 .../appkit/hooks/jettons/use-jetton-info.tsx | 0 .../jettons/use-jetton-wallet-address.tsx | 10 +- .../hooks/jettons/use-jettons-by-address.tsx | 0 .../src/appkit/hooks/jettons/use-jettons.tsx | 0 .../hooks/jettons/use-transfer-jetton.tsx | 0 .../jettons/use-watch-jettons-by-address.tsx | 0 .../hooks/jettons/use-watch-jettons.tsx | 0 .../appkit/hooks/network/networks.test.tsx | 0 .../appkit/hooks/network/use-block-number.tsx | 0 .../hooks/network/use-default-network.tsx | 0 .../src/appkit/hooks/network/use-network.tsx | 0 .../src/appkit/hooks/network/use-networks.tsx | 0 .../src/appkit/hooks/nft/nfts.test.tsx | 7 +- .../examples/src/appkit/hooks/nft/use-nft.tsx | 2 +- .../appkit/hooks/nft/use-nfts-by-address.tsx | 2 +- .../src/appkit/hooks/nft/use-nfts.tsx | 2 +- .../src/appkit/hooks/nft/use-transfer-nft.tsx | 0 .../onramp/use-crypto-onramp-provider.tsx | 0 .../onramp/use-crypto-onramp-providers.tsx | 0 .../src/appkit/hooks/signing/signing.test.tsx | 0 .../appkit/hooks/signing/use-sign-binary.tsx | 0 .../appkit/hooks/signing/use-sign-cell.tsx | 0 .../appkit/hooks/signing/use-sign-text.tsx | 0 .../src/appkit/hooks/staking/staking.test.tsx | 0 .../staking/use-build-stake-transaction.tsx | 0 .../hooks/staking/use-staked-balance.tsx | 0 .../staking/use-staking-provider-info.tsx | 0 .../staking/use-staking-provider-metadata.tsx | 0 .../hooks/staking/use-staking-provider.tsx | 0 .../hooks/staking/use-staking-providers.tsx | 0 .../hooks/staking/use-staking-quote.tsx | 0 .../src/appkit/hooks/swap/swap.test.tsx | 0 .../hooks/swap/use-build-swap-transaction.tsx | 0 .../appkit/hooks/swap/use-swap-provider.tsx | 0 .../appkit/hooks/swap/use-swap-providers.tsx | 0 .../src/appkit/hooks/swap/use-swap-quote.tsx | 0 .../hooks/transaction/transaction.test.tsx | 0 .../transaction/use-send-transaction.tsx | 0 .../hooks/transaction/use-transfer-ton.tsx | 0 .../use-watch-transactions-by-address.tsx | 0 .../transaction/use-watch-transactions.tsx | 0 .../src/appkit/hooks/wallets/use-address.tsx | 0 .../src/appkit/hooks/wallets/use-connect.tsx | 0 .../hooks/wallets/use-connected-wallets.tsx | 2 +- .../hooks/wallets/use-connector-by-id.tsx | 0 .../appkit/hooks/wallets/use-connectors.tsx | 0 .../appkit/hooks/wallets/use-disconnect.tsx | 0 .../hooks/wallets/use-selected-wallet.tsx | 0 .../src/appkit/hooks/wallets/wallets.test.tsx | 0 .../examples/src/appkit/setup-react.tsx | 0 {demo => docs}/examples/src/appkit/setup.ts | 0 .../appkit/staking/staking-providers.test.ts | 23 + .../src/appkit/staking/staking-widget.tsx | 0 .../examples/src/appkit/staking/tonstakers.ts | 0 .../examples/src/appkit/swap/dedust.ts | 0 .../examples/src/appkit/swap/omniston.ts | 0 .../src/appkit/swap/swap-providers.test.ts | 47 + .../examples/src/appkit/swap/swap-widget.tsx | 0 {demo => docs}/examples/src/initialize.ts | 0 {demo => docs}/examples/src/jettons.ts | 0 .../src/lib/wallet-kit-initialize-sample.ts | 0 .../examples/src/lib/wallet-manifest.ts | 0 {demo => docs}/examples/src/requests.ts | 2 +- {demo => docs}/examples/src/send-jettons.ts | 0 {demo => docs}/examples/src/send-nft.ts | 0 {demo => docs}/examples/src/send-ton.ts | 0 .../examples/src/ui-state-wiring.ts | 0 .../src/ui/render-connect-preview.tsx | 0 .../examples/src/ui/render-money-flow.tsx | 0 .../src/ui/render-sign-data-preview.tsx | 0 .../examples/src/ui/summarize-transaction.tsx | 0 {demo => docs}/examples/tsconfig.json | 0 {demo => docs}/examples/vitest.config.ts | 0 docs/reference-generator/package.json | 18 + docs/reference-generator/src/collect.ts | 235 + docs/reference-generator/src/extract.ts | 982 ++++ docs/reference-generator/src/index.ts | 114 + docs/reference-generator/src/render.ts | 463 ++ docs/reference-generator/tsconfig.json | 15 + docs/template-resolver/package.json | 19 + .../template-resolver/src}/extract-samples.ts | 0 .../template-resolver/src/index.ts | 35 +- docs/template-resolver/tsconfig.json | 15 + .../packages/appkit-react/README.md | 14 +- .../packages/appkit-react/docs/components.md | 18 +- .../packages/appkit-react/docs/hooks.md | 98 +- .../packages/appkit-react/docs/reference.md | 3415 +++++++++++++ .../templates}/packages/appkit/README.md | 6 +- .../packages/appkit/docs/actions.md | 122 +- .../packages/appkit/docs/connectors.md | 6 +- .../packages/appkit/docs/reference.md | 4075 +++++++++++++++ .../packages/appkit/docs/staking.md | 4 +- .../templates}/packages/appkit/docs/swap.md | 4 +- .../templates}/packages/walletkit/README.md | 28 +- .../src/defi/crypto-onramp/README.md | 0 .../defi/crypto-onramp/layerswap/README.md | 0 .../defi/crypto-onramp/swaps-xyz/README.md | 0 .../walletkit/src/defi/staking/README.md | 2 +- .../src/defi/staking/tonstakers/README.md | 6 +- .../walletkit/src/defi/swap/README.md | 0 .../walletkit/src/defi/swap/dedust/README.md | 8 +- .../src/defi/swap/omniston/README.md | 10 +- eslint.config.js | 2 +- package.json | 4 +- packages/appkit-react/README.md | 4 +- packages/appkit-react/docs/components.md | 4 +- .../docs/creating-swap-provider.md | 2 +- packages/appkit-react/docs/hooks.md | 16 +- packages/appkit-react/docs/reference.md | 4046 +++++++++++++++ .../shared/amount-presets/amount-presets.tsx | 29 + .../shared/copy-button/copy-button.tsx | 18 +- .../shared/currency-item/currency-item.tsx | 32 + .../currency-select-modal.tsx | 65 + .../low-balance-modal/low-balance-modal.tsx | 30 +- .../option-switcher/option-switcher.tsx | 25 +- .../settings-button/settings-button.tsx | 17 + .../token-select-modal/token-select-modal.tsx | 53 + .../shared/token-selector/token-selector.tsx | 23 +- .../src/components/ui/block/block.tsx | 17 + .../src/components/ui/button/button.tsx | 43 + .../centered-amount-input.tsx | 22 + .../components/ui/collapsible/collapsible.tsx | 17 + .../src/components/ui/icons/check-icon.tsx | 3 + .../components/ui/icons/chevron-down-icon.tsx | 3 + .../src/components/ui/icons/chevrons-icon.tsx | 3 + .../src/components/ui/icons/close-icon.tsx | 3 + .../src/components/ui/icons/copy-icon.tsx | 3 + .../src/components/ui/icons/failed-icon.tsx | 3 + .../src/components/ui/icons/flip-icon.tsx | 3 + .../src/components/ui/icons/image-icon.tsx | 3 + .../src/components/ui/icons/search-icon.tsx | 3 + .../src/components/ui/icons/sliders-icon.tsx | 3 + .../src/components/ui/icons/spinner-icon.tsx | 3 + .../src/components/ui/icons/success-icon.tsx | 3 + .../src/components/ui/icons/ton-icon.tsx | 14 + .../src/components/ui/icons/types.ts | 13 +- .../src/components/ui/icons/verified-icon.tsx | 3 + .../components/ui/info-block/info-block.tsx | 15 + .../src/components/ui/input/input.tsx | 61 + .../logo-with-network/logo-with-network.tsx | 28 +- .../src/components/ui/logo/logo.tsx | 20 + .../src/components/ui/modal/modal.tsx | 40 +- .../src/components/ui/select/select.tsx | 44 + .../src/components/ui/skeleton/skeleton.tsx | 18 + .../src/components/ui/tabs/tabs.tsx | 67 + .../send-jetton-button/send-jetton-button.tsx | 20 + .../send-ton-button/send-ton-button.tsx | 19 + .../balances/hooks/use-balance-by-address.ts | 26 +- .../features/balances/hooks/use-balance.ts | 26 +- .../hooks/use-watch-balance-by-address.ts | 19 +- .../balances/hooks/use-watch-balance.ts | 19 +- .../hooks/use-jetton-balance-by-address.ts | 26 +- .../features/jettons/hooks/use-jetton-info.ts | 26 +- .../hooks/use-jetton-wallet-address.ts | 26 +- .../jettons/hooks/use-jettons-by-address.ts | 26 +- .../src/features/jettons/hooks/use-jettons.ts | 26 +- .../jettons/hooks/use-transfer-jetton.ts | 27 + .../hooks/use-watch-jettons-by-address.ts | 19 +- .../jettons/hooks/use-watch-jettons.ts | 19 +- .../network/hooks/use-block-number.ts | 24 +- .../network/hooks/use-default-network.ts | 15 +- .../src/features/network/hooks/use-network.ts | 15 +- .../features/network/hooks/use-networks.ts | 15 +- .../nft/components/nft-item/nft-item.tsx | 17 + .../src/features/nft/hooks/use-nft.ts | 28 +- .../features/nft/hooks/use-nfts-by-address.ts | 28 +- .../src/features/nft/hooks/use-nfts.ts | 26 +- .../features/nft/hooks/use-transfer-nft.ts | 27 + .../onramp-amount-reversed.tsx | 7 + .../onramp-currency-item.tsx | 7 + .../onramp-currency-select-modal.tsx | 11 + .../onramp-provider-item.tsx | 7 + .../onramp-provider-select.tsx | 10 + .../onramp-token-selectors.tsx | 18 + .../onramp/hooks/use-build-onramp-url.ts | 2 +- .../hooks/use-create-crypto-onramp-deposit.ts | 24 +- .../hooks/use-crypto-onramp-provider.ts | 34 +- .../hooks/use-crypto-onramp-providers.ts | 15 +- .../onramp/hooks/use-crypto-onramp-quote.ts | 24 +- .../onramp/hooks/use-crypto-onramp-status.ts | 24 +- .../onramp/hooks/use-onramp-provider.ts | 7 +- .../onramp/hooks/use-onramp-providers.ts | 3 +- .../features/onramp/hooks/use-onramp-quote.ts | 2 +- .../appkit-react/src/features/onramp/index.ts | 6 +- .../appkit-react/src/features/onramp/types.ts | 81 +- .../crypto-onramp-context.ts | 85 +- .../crypto-onramp-widget-provider.tsx | 24 +- .../crypto-onramp-widget-ui.tsx | 14 + .../crypto-onramp-widget.tsx | 21 +- .../widgets/crypto-onramp/utils/chains.ts | 25 +- .../onramp-widget-provider.tsx | 4 +- .../widgets/ton-pay-widget/ton-pay-widget.tsx | 22 +- .../settings/hooks/use-app-kit-theme.ts | 16 + .../features/settings/hooks/use-app-kit.ts | 9 + .../src/features/settings/hooks/use-i18n.ts | 9 + .../features/signing/hooks/use-sign-binary.ts | 29 +- .../features/signing/hooks/use-sign-cell.ts | 30 +- .../features/signing/hooks/use-sign-text.ts | 29 +- .../select-unstake-mode.tsx | 20 + .../staking-balance-block.tsx | 40 +- .../components/staking-info/staking-info.tsx | 20 + .../staking-settings-modal.tsx | 22 + .../staking-widget-provider.tsx | 38 +- .../staking-widget-ui/staking-widget-ui.tsx | 14 + .../staking-widget/staking-widget.tsx | 20 +- .../hooks/use-build-stake-transaction.ts | 15 +- .../staking/hooks/use-staked-balance.ts | 25 +- .../hooks/use-staking-provider-info.ts | 27 +- .../hooks/use-staking-provider-metadata.ts | 27 +- .../staking/hooks/use-staking-provider.ts | 34 +- .../staking/hooks/use-staking-providers.ts | 15 +- .../staking/hooks/use-staking-quote.ts | 25 +- .../src/features/staking/index.ts | 6 +- .../swap-field/swap-field.stories.tsx | 9 - .../swap/components/swap-field/swap-field.tsx | 28 +- .../swap-flip-button/swap-flip-button.tsx | 18 + .../swap/components/swap-info/swap-info.tsx | 21 + .../swap-settings-modal.tsx | 21 + .../swap-token-select-modal.tsx | 14 + .../swap-widget-provider.tsx | 46 +- .../swap-widget-ui/swap-widget-ui.tsx | 20 +- .../components/swap-widget/swap-widget.tsx | 23 +- .../swap/hooks/use-build-swap-transaction.ts | 24 +- .../features/swap/hooks/use-swap-provider.ts | 16 +- .../features/swap/hooks/use-swap-providers.ts | 15 +- .../src/features/swap/hooks/use-swap-quote.ts | 24 +- .../transaction-progress.tsx | 2 +- .../transaction-provider/send-provider.tsx | 8 +- .../components/transaction/send.tsx | 10 +- .../transaction/hooks/use-send-transaction.ts | 25 + .../hooks/use-transaction-status.ts | 37 +- .../transaction/hooks/use-transfer-ton.ts | 25 + .../use-watch-transactions-by-address.ts | 18 +- .../hooks/use-watch-transactions.ts | 19 +- .../src/features/wallets/hooks/use-address.ts | 15 +- .../src/features/wallets/hooks/use-connect.ts | 25 + .../wallets/hooks/use-connected-wallets.ts | 16 + .../wallets/hooks/use-connector-by-id.ts | 10 + .../features/wallets/hooks/use-connectors.ts | 16 + .../features/wallets/hooks/use-disconnect.ts | 25 + .../wallets/hooks/use-selected-wallet.ts | 15 +- packages/appkit-react/src/index.ts | 1 + .../src/providers/app-kit-provider.tsx | 17 + .../src/providers/i18n-provider.tsx | 29 + .../appkit-react/src/types/appkit-ui-token.ts | 23 +- .../appkit-react/src/utils/map-defi-error.ts | 2 +- packages/appkit/README.md | 4 +- packages/appkit/docs/actions.md | 26 +- packages/appkit/docs/connectors.md | 2 +- packages/appkit/docs/reference.md | 4528 +++++++++++++++++ packages/appkit/docs/staking.md | 2 +- packages/appkit/docs/swap.md | 2 +- .../balances/get-balance-by-address.ts | 37 +- .../src/actions/balances/get-balance.ts | 34 +- .../balances/watch-balance-by-address.ts | 36 +- .../src/actions/balances/watch-balance.ts | 33 +- .../src/actions/connectors/add-connector.ts | 30 +- .../appkit/src/actions/connectors/connect.ts | 28 +- .../src/actions/connectors/disconnect.ts | 28 +- .../actions/connectors/get-connector-by-id.ts | 28 +- .../src/actions/connectors/get-connectors.ts | 18 +- .../connectors/watch-connector-by-id.ts | 29 +- .../actions/connectors/watch-connectors.ts | 28 +- .../create-crypto-onramp-deposit.ts | 27 +- .../get-crypto-onramp-provider.ts | 31 +- .../get-crypto-onramp-providers.ts | 21 +- .../crypto-onramp/get-crypto-onramp-quote.ts | 27 +- .../crypto-onramp/get-crypto-onramp-status.ts | 27 +- .../watch-crypto-onramp-providers.ts | 27 +- packages/appkit/src/actions/index.ts | 2 +- .../create-transfer-jetton-transaction.ts | 44 +- .../src/actions/jettons/get-jetton-balance.ts | 41 +- .../src/actions/jettons/get-jetton-info.ts | 38 +- .../jettons/get-jetton-wallet-address.ts | 38 +- .../actions/jettons/get-jettons-by-address.ts | 41 +- .../appkit/src/actions/jettons/get-jettons.ts | 38 +- .../src/actions/jettons/transfer-jetton.ts | 32 +- .../jettons/watch-jettons-by-address.ts | 35 +- .../src/actions/jettons/watch-jettons.ts | 32 +- .../src/actions/network/get-api-client.ts | 32 +- .../src/actions/network/get-block-number.ts | 31 +- .../actions/network/get-default-network.ts | 18 +- .../appkit/src/actions/network/get-network.ts | 18 +- .../src/actions/network/get-networks.ts | 18 +- .../actions/network/has-streaming-provider.ts | 19 +- .../actions/network/set-default-network.ts | 29 +- .../actions/network/watch-default-network.ts | 28 +- .../src/actions/network/watch-networks.ts | 28 +- .../nft/create-transfer-nft-transaction.ts | 41 +- packages/appkit/src/actions/nft/get-nft.ts | 37 +- .../src/actions/nft/get-nfts-by-address.ts | 41 +- packages/appkit/src/actions/nft/get-nfts.ts | 38 +- .../appkit/src/actions/nft/transfer-nft.ts | 32 +- .../src/actions/onramp/build-onramp-url.ts | 5 +- .../src/actions/onramp/get-onramp-manager.ts | 5 +- .../src/actions/onramp/get-onramp-provider.ts | 5 +- .../actions/onramp/get-onramp-providers.ts | 5 +- .../src/actions/onramp/get-onramp-quote.ts | 7 +- .../actions/onramp/watch-onramp-providers.ts | 2 +- .../actions/providers/register-provider.ts | 21 +- .../appkit/src/actions/signing/sign-binary.ts | 35 +- .../appkit/src/actions/signing/sign-cell.ts | 41 +- .../appkit/src/actions/signing/sign-text.ts | 35 +- .../staking/build-stake-transaction.ts | 33 +- .../src/actions/staking/get-staked-balance.ts | 35 +- .../actions/staking/get-staking-manager.ts | 19 +- .../staking/get-staking-provider-info.ts | 35 +- .../staking/get-staking-provider-metadata.ts | 35 +- .../actions/staking/get-staking-provider.ts | 33 +- .../actions/staking/get-staking-providers.ts | 21 +- .../src/actions/staking/get-staking-quote.ts | 31 +- .../staking/set-default-staking-provider.ts | 27 +- .../staking/watch-staking-providers.ts | 27 +- .../actions/swap/build-swap-transaction.ts | 27 +- .../src/actions/swap/get-swap-manager.ts | 21 +- .../src/actions/swap/get-swap-provider.ts | 32 +- .../src/actions/swap/get-swap-providers.ts | 21 +- .../appkit/src/actions/swap/get-swap-quote.ts | 31 +- .../actions/swap/set-default-swap-provider.ts | 28 +- .../src/actions/swap/watch-swap-providers.ts | 28 +- .../create-transfer-ton-transaction.ts | 49 +- .../transaction/get-transaction-status.ts | 46 +- .../actions/transaction/send-transaction.ts | 30 +- .../src/actions/transaction/transfer-ton.ts | 30 +- .../watch-transactions-by-address.ts | 35 +- .../actions/transaction/watch-transactions.ts | 32 +- .../actions/wallets/get-connected-wallets.ts | 18 +- .../actions/wallets/get-selected-wallet.ts | 18 +- .../actions/wallets/set-selected-wallet-id.ts | 27 +- .../wallets/watch-connected-wallets.ts | 28 +- .../actions/wallets/watch-selected-wallet.ts | 28 +- .../adapters/ton-connect-wallet-adapter.ts | 33 +- .../connectors/ton-connect-connector.ts | 36 +- .../src/connectors/tonconnect/constants/id.ts | 7 + .../appkit/src/connectors/tonconnect/index.ts | 10 +- .../tonconnect/utils/transaction.ts | 6 +- .../src/core/app-kit/constants/events.ts | 21 +- .../src/core/app-kit/services/app-kit.ts | 56 +- .../appkit/src/core/app-kit/types/config.ts | 35 +- .../appkit/src/core/app-kit/types/events.ts | 54 + packages/appkit/src/core/emitter/index.ts | 58 +- packages/appkit/src/core/network/index.ts | 3 +- .../services/app-kit-network-manager.ts | 24 +- packages/appkit/src/core/network/walletkit.ts | 70 + packages/appkit/src/core/streaming/index.ts | 54 +- .../services/wallets-manager.ts | 21 +- packages/appkit/src/crypto-onramp/index.ts | 78 +- .../src/crypto-onramp/layerswap/index.ts | 54 +- .../src/crypto-onramp/swaps-xyz/index.ts | 61 +- packages/appkit/src/index.ts | 3 +- packages/appkit/src/onramp/index.ts | 4 + packages/appkit/src/queries/index.ts | 2 +- .../jettons/get-jetton-balance-by-address.ts | 2 +- .../jettons/get-jetton-wallet-address.ts | 3 +- packages/appkit/src/queries/nft/get-nft.ts | 3 +- packages/appkit/src/staking/index.ts | 81 +- .../appkit/src/staking/tonstakers/index.ts | 40 +- packages/appkit/src/swap/dedust/index.ts | 69 +- packages/appkit/src/swap/index.ts | 154 +- packages/appkit/src/swap/omniston/index.ts | 60 +- .../src/types/{balance.ts => api-client.ts} | 4 +- packages/appkit/src/types/client.ts | 37 + packages/appkit/src/types/connector.ts | 64 +- packages/appkit/src/types/jetton.ts | 40 +- packages/appkit/src/types/network.ts | 28 +- packages/appkit/src/types/nft.ts | 38 + packages/appkit/src/types/primitives.ts | 48 + packages/appkit/src/types/provider.ts | 25 +- packages/appkit/src/types/query.ts | 43 +- packages/appkit/src/types/signing.ts | 72 +- packages/appkit/src/types/transaction.ts | 64 +- packages/appkit/src/types/utils.ts | 8 +- packages/appkit/src/types/wallet.ts | 35 +- .../src/utils/amount/calc-fiat-value.ts | 3 +- .../src/utils/balance/calc-max-spendable.ts | 8 +- .../src/utils/balance/get-ton-shortfall.ts | 4 +- .../appkit/src/utils/functions/debounce.ts | 5 +- packages/appkit/src/utils/index.ts | 21 +- .../appkit/src/utils/jetton/jetton-info.ts | 2 +- .../src/utils/network/resolve-network.ts | 2 +- packages/appkit/src/utils/nft/nft-info.ts | 3 +- .../mcp/src/tools/wallet-management-tools.ts | 4 +- packages/walletkit/README.md | 4 +- .../src/api/interfaces/CryptoOnrampAPI.ts | 1 + .../src/api/interfaces/DefiManagerAPI.ts | 1 + .../src/api/interfaces/DefiProvider.ts | 1 + .../walletkit/src/api/interfaces/index.ts | 2 +- .../api/models/blockchain/MasterchainInfo.ts | 6 +- .../src/api/models/bridge/BridgeEvent.ts | 12 +- .../models/bridge/ConnectionRequestEvent.ts | 12 +- .../api/models/bridge/DisconnectionEvent.ts | 6 +- .../api/models/bridge/RequestErrorEvent.ts | 6 +- .../bridge/SendTransactionApprovalResponse.ts | 2 +- .../bridge/SendTransactionRequestEvent.ts | 6 +- .../models/bridge/SignDataApprovalResponse.ts | 4 +- .../api/models/bridge/SignDataRequestEvent.ts | 8 +- .../src/api/models/core/AddressBook.ts | 6 +- .../src/api/models/core/AssetType.ts | 2 +- .../src/api/models/core/BaseProvider.ts | 6 + .../walletkit/src/api/models/core/DAppInfo.ts | 4 +- .../walletkit/src/api/models/core/Network.ts | 2 +- .../src/api/models/core/PreparedSignData.ts | 18 +- .../src/api/models/core/Primitives.ts | 12 +- .../src/api/models/core/ProofMessage.ts | 10 +- .../walletkit/src/api/models/core/SendMode.ts | 10 +- .../walletkit/src/api/models/core/SignData.ts | 8 +- .../src/api/models/core/TokenAnimation.ts | 2 +- .../src/api/models/core/TokenInfo.ts | 8 +- .../crypto-onramp/CryptoOnrampDeposit.ts | 13 +- .../CryptoOnrampDepositParams.ts | 4 +- .../CryptoOnrampProviderMetadata.ts | 10 +- .../models/crypto-onramp/CryptoOnrampQuote.ts | 10 +- .../crypto-onramp/CryptoOnrampQuoteParams.ts | 6 +- .../crypto-onramp/CryptoOnrampStatus.ts | 6 +- .../crypto-onramp/CryptoOnrampStatusParams.ts | 10 +- packages/walletkit/src/api/models/index.ts | 2 +- .../src/api/models/jettons/Jetton.ts | 14 +- .../src/api/models/jettons/JettonsRequest.ts | 2 +- .../src/api/models/jettons/JettonsResponse.ts | 4 +- .../models/jettons/JettonsTransferRequest.ts | 8 +- packages/walletkit/src/api/models/nfts/NFT.ts | 22 +- .../src/api/models/nfts/NFTAttribute.ts | 2 +- .../src/api/models/nfts/NFTCollection.ts | 18 +- .../api/models/nfts/NFTRawTransferRequest.ts | 4 +- .../src/api/models/nfts/NFTTransferRequest.ts | 6 +- .../src/api/models/nfts/NFTsRequest.ts | 4 +- .../src/api/models/nfts/NFTsResponse.ts | 4 +- .../src/api/models/nfts/UserNFTsRequest.ts | 4 +- .../src/api/models/onramp/OnrampLimits.ts | 12 +- .../src/api/models/onramp/OnrampParams.ts | 8 +- .../src/api/models/onramp/OnrampQuote.ts | 10 +- .../api/models/onramp/OnrampQuoteParams.ts | 6 +- .../api/models/sessions/TONConnectSession.ts | 4 +- .../src/api/models/staking/StakeParams.ts | 8 +- .../src/api/models/staking/StakingBalance.ts | 12 +- .../api/models/staking/StakingProviderInfo.ts | 6 +- .../models/staking/StakingProviderMetadata.ts | 20 +- .../src/api/models/staking/StakingQuote.ts | 18 +- .../models/staking/StakingQuoteDirection.ts | 2 +- .../api/models/staking/StakingQuoteParams.ts | 12 +- .../src/api/models/staking/UnstakeMode.ts | 2 +- .../src/api/models/streaming/BalanceUpdate.ts | 8 +- .../src/api/models/streaming/JettonUpdate.ts | 10 +- .../models/streaming/StreamingBaseUpdate.ts | 4 +- .../api/models/streaming/StreamingEvents.ts | 3 + .../models/streaming/TransactionsUpdate.ts | 12 +- .../src/api/models/swaps/SwapParams.ts | 10 +- .../src/api/models/swaps/SwapQuote.ts | 24 +- .../src/api/models/swaps/SwapQuoteParams.ts | 10 +- .../src/api/models/swaps/SwapToken.ts | 8 +- .../src/api/models/tons/TONTransferRequest.ts | 10 +- .../transactions/SendTransactionResponse.ts | 6 +- .../api/models/transactions/Transaction.ts | 152 +- .../transactions/TransactionMetadata.ts | 28 +- .../models/transactions/TransactionRequest.ts | 16 +- .../models/transactions/TransactionStatus.ts | 2 +- .../models/transactions/TransactionTrace.ts | 52 +- .../transactions/TransactionTraceMoneyFlow.ts | 14 +- .../emulation/TransactionEmulatedPreview.ts | 6 +- .../emulation/TransactionEmulatedTrace.ts | 8 +- .../walletkit/src/bridge/core/BridgeConfig.ts | 2 +- .../walletkit/src/clients/BaseApiClient.ts | 6 + .../src/clients/tonapi/ApiClientTonApi.ts | 4 + .../clients/toncenter/ApiClientToncenter.ts | 9 +- .../walletkit/src/clients/toncenter/index.ts | 2 + packages/walletkit/src/core/BridgeManager.ts | 28 +- packages/walletkit/src/core/EventEmitter.ts | 12 +- packages/walletkit/src/core/EventProcessor.ts | 24 +- packages/walletkit/src/core/EventRouter.ts | 22 +- packages/walletkit/src/core/EventStore.ts | 18 +- packages/walletkit/src/core/Initializer.ts | 16 +- packages/walletkit/src/core/JettonsManager.ts | 18 +- packages/walletkit/src/core/Logger.ts | 32 +- packages/walletkit/src/core/NetworkManager.ts | 13 +- .../walletkit/src/core/RequestProcessor.ts | 28 +- .../core/TONConnectStoredSessionManager.ts | 16 +- packages/walletkit/src/core/TonWalletKit.ts | 47 +- packages/walletkit/src/core/WalletManager.ts | 18 +- .../crypto-onramp/CryptoOnrampProvider.ts | 18 +- .../src/defi/crypto-onramp/README.md | 12 +- .../src/defi/crypto-onramp/errors.ts | 12 + .../LayerswapCryptoOnrampProvider.ts | 16 +- .../defi/crypto-onramp/layerswap/README.md | 4 +- .../src/defi/crypto-onramp/layerswap/utils.ts | 2 +- .../defi/crypto-onramp/swaps-xyz/README.md | 4 +- .../swaps-xyz/SwapsXyzCryptoOnrampProvider.ts | 11 +- .../src/defi/crypto-onramp/swaps-xyz/utils.ts | 4 +- packages/walletkit/src/defi/errors.ts | 16 + packages/walletkit/src/defi/onramp/errors.ts | 4 + .../defi/onramp/mercuryo/MercuryoProvider.ts | 10 +- .../defi/onramp/moonpay/MoonpayProvider.ts | 4 +- .../src/defi/onramp/ton-pay/TonPayProvider.ts | 4 +- packages/walletkit/src/defi/staking/README.md | 4 +- .../src/defi/staking/StakingManager.ts | 1 + .../src/defi/staking/StakingProvider.ts | 1 + packages/walletkit/src/defi/staking/errors.ts | 7 + .../src/defi/staking/tonstakers/README.md | 8 +- .../tonstakers/TonStakersStakingProvider.ts | 4 +- .../src/defi/staking/tonstakers/index.ts | 2 +- .../models/TonStakersProviderConfig.ts | 14 +- .../defi/staking/tonstakers/models/index.ts | 2 +- packages/walletkit/src/defi/swap/README.md | 2 +- .../walletkit/src/defi/swap/SwapManager.ts | 1 + .../walletkit/src/defi/swap/SwapProvider.ts | 20 +- .../defi/swap/dedust/DeDustPrivateTypes.ts | 12 +- .../defi/swap/dedust/DeDustSwapProvider.ts | 24 +- .../walletkit/src/defi/swap/dedust/README.md | 2 +- .../dedust/models/DeDustProviderOptions.ts | 12 +- .../swap/dedust/models/DeDustQuoteMetadata.ts | 2 +- .../dedust/models/DeDustReferralOptions.ts | 4 +- .../dedust/models/DeDustSwapProviderConfig.ts | 4 +- .../walletkit/src/defi/swap/dedust/utils.ts | 8 +- packages/walletkit/src/defi/swap/errors.ts | 10 + .../swap/omniston/OmnistonSwapProvider.ts | 22 +- .../src/defi/swap/omniston/README.md | 4 +- .../models/OmnistonProviderOptions.ts | 2 +- .../omniston/models/OmnistonQuoteMetadata.ts | 4 +- .../models/OmnistonReferrerOptions.ts | 6 +- .../omniston/models/OmnistonSwapOptions.ts | 2 +- .../models/OmnistonSwapProviderConfig.ts | 6 +- packages/walletkit/src/index.ts | 1 + packages/walletkit/src/types/config.ts | 31 +- packages/walletkit/src/types/durableEvents.ts | 68 +- packages/walletkit/src/types/factory.ts | 9 +- packages/walletkit/src/types/internal.ts | 6 +- packages/walletkit/src/types/jettons.ts | 16 +- packages/walletkit/src/types/jsBridge.ts | 4 +- packages/walletkit/src/types/kit.ts | 56 +- .../src/types/toncenter/AccountEvent.ts | 6 +- .../src/types/toncenter/ApiClient.ts | 18 + .../src/types/toncenter/parsers/body.ts | 6 +- .../parsers/handlers/JettonHandler.ts | 4 +- .../src/types/toncenter/parsers/index.ts | 2 +- .../types/toncenter/parsers/messageDecoder.ts | 32 +- .../types/toncenter/parsers/messageHandler.ts | 46 +- .../src/types/toncenter/parsers/opcodes.ts | 16 +- pnpm-lock.yaml | 174 +- pnpm-workspace.yaml | 1 + 672 files changed, 26695 insertions(+), 1978 deletions(-) create mode 100644 .claude/skills/document-public-api/SKILL.md rename {demo => docs}/examples/.gitignore (100%) rename {demo => docs}/examples/env.d.ts (100%) rename {demo => docs}/examples/index.html (100%) rename {demo => docs}/examples/package.json (100%) rename {demo => docs}/examples/src/__mocks__/@ton/walletkit.ts (100%) rename {demo => docs}/examples/src/__mocks__/@tonconnect/sdk.ts (100%) rename {demo => docs}/examples/src/__mocks__/@tonconnect/ui-react.ts (100%) rename {demo => docs}/examples/src/__tests__/initialize.test.ts (100%) rename {demo => docs}/examples/src/__tests__/jettons.test.ts (100%) rename {demo => docs}/examples/src/__tests__/requests.test.ts (100%) rename {demo => docs}/examples/src/__tests__/setup.ts (100%) rename {demo => docs}/examples/src/__tests__/test-utils.tsx (100%) rename {demo => docs}/examples/src/__tests__/transfers.test.ts (100%) rename {demo => docs}/examples/src/__tests__/ui-state-wiring.test.ts (100%) rename {demo => docs}/examples/src/__tests__/ui.test.ts (100%) rename {demo => docs}/examples/src/__tests__/wallet-kit-initialize-sample.test.ts (100%) rename {demo => docs}/examples/src/appkit/actions/balances/balances.test.ts (92%) rename {demo => docs}/examples/src/appkit/actions/balances/get-balance-by-address.ts (86%) rename {demo => docs}/examples/src/appkit/actions/balances/get-balance.ts (89%) rename {demo => docs}/examples/src/appkit/actions/balances/watch-balance-by-address.ts (100%) rename {demo => docs}/examples/src/appkit/actions/balances/watch-balance.ts (100%) rename {demo => docs}/examples/src/appkit/actions/connectors/add-connector.ts (87%) rename {demo => docs}/examples/src/appkit/actions/connectors/connect.ts (100%) rename {demo => docs}/examples/src/appkit/actions/connectors/connectors.test.ts (90%) rename {demo => docs}/examples/src/appkit/actions/connectors/disconnect.ts (100%) rename {demo => docs}/examples/src/appkit/actions/connectors/get-connector-by-id.ts (100%) rename {demo => docs}/examples/src/appkit/actions/connectors/get-connectors.ts (100%) rename {demo => docs}/examples/src/appkit/actions/connectors/watch-connector-by-id.ts (100%) rename {demo => docs}/examples/src/appkit/actions/connectors/watch-connectors.ts (100%) rename {demo => docs}/examples/src/appkit/actions/jettons/create-transfer-jetton-transaction.ts (100%) rename {demo => docs}/examples/src/appkit/actions/jettons/get-jetton-balance.ts (93%) rename {demo => docs}/examples/src/appkit/actions/jettons/get-jetton-info.ts (100%) rename {demo => docs}/examples/src/appkit/actions/jettons/get-jetton-wallet-address.ts (100%) rename {demo => docs}/examples/src/appkit/actions/jettons/get-jettons-by-address.ts (96%) rename {demo => docs}/examples/src/appkit/actions/jettons/get-jettons.ts (95%) rename {demo => docs}/examples/src/appkit/actions/jettons/jettons.test.ts (98%) rename {demo => docs}/examples/src/appkit/actions/jettons/transfer-jetton.ts (100%) rename {demo => docs}/examples/src/appkit/actions/network/get-api-client.ts (100%) rename {demo => docs}/examples/src/appkit/actions/network/get-block-number.ts (100%) rename {demo => docs}/examples/src/appkit/actions/network/get-default-network.ts (100%) rename {demo => docs}/examples/src/appkit/actions/network/get-network.ts (100%) rename {demo => docs}/examples/src/appkit/actions/network/get-networks.ts (100%) rename {demo => docs}/examples/src/appkit/actions/network/has-streaming-provider.ts (100%) rename {demo => docs}/examples/src/appkit/actions/network/network.test.ts (100%) rename {demo => docs}/examples/src/appkit/actions/network/set-default-network.ts (100%) rename {demo => docs}/examples/src/appkit/actions/network/watch-default-network.ts (100%) rename {demo => docs}/examples/src/appkit/actions/network/watch-networks.ts (100%) rename {demo => docs}/examples/src/appkit/actions/nft/create-transfer-nft-transaction.ts (100%) rename {demo => docs}/examples/src/appkit/actions/nft/get-nft.ts (100%) rename {demo => docs}/examples/src/appkit/actions/nft/get-nfts-by-address.ts (96%) rename {demo => docs}/examples/src/appkit/actions/nft/get-nfts.ts (100%) rename {demo => docs}/examples/src/appkit/actions/nft/nfts.test.ts (100%) rename {demo => docs}/examples/src/appkit/actions/nft/transfer-nft.ts (100%) rename {demo => docs}/examples/src/appkit/actions/onramp/build-onramp-url.ts (100%) rename {demo => docs}/examples/src/appkit/actions/onramp/get-crypto-onramp-provider.ts (100%) rename {demo => docs}/examples/src/appkit/actions/onramp/get-crypto-onramp-providers.ts (100%) rename {demo => docs}/examples/src/appkit/actions/onramp/get-onramp-quote.ts (100%) rename {demo => docs}/examples/src/appkit/actions/providers/register-provider.ts (100%) rename {demo => docs}/examples/src/appkit/actions/signing/sign-binary.ts (100%) rename {demo => docs}/examples/src/appkit/actions/signing/sign-cell.ts (99%) rename {demo => docs}/examples/src/appkit/actions/signing/sign-text.ts (100%) rename {demo => docs}/examples/src/appkit/actions/signing/signing.test.ts (100%) rename {demo => docs}/examples/src/appkit/actions/staking/staking-actions.ts (97%) rename {demo => docs}/examples/src/appkit/actions/staking/staking.test.ts (100%) rename {demo => docs}/examples/src/appkit/actions/swap/swap-actions.ts (100%) rename {demo => docs}/examples/src/appkit/actions/swap/swap.test.ts (100%) rename {demo => docs}/examples/src/appkit/actions/transaction/create-transfer-ton-transaction.ts (91%) rename {demo => docs}/examples/src/appkit/actions/transaction/send-transaction.ts (100%) rename {demo => docs}/examples/src/appkit/actions/transaction/transaction.test.ts (100%) rename {demo => docs}/examples/src/appkit/actions/transaction/transfer-ton.ts (100%) rename {demo => docs}/examples/src/appkit/actions/wallets/get-connected-wallets.ts (100%) rename {demo => docs}/examples/src/appkit/actions/wallets/get-selected-wallet.ts (100%) rename {demo => docs}/examples/src/appkit/actions/wallets/set-selected-wallet-id.ts (100%) rename {demo => docs}/examples/src/appkit/actions/wallets/wallets.test.ts (100%) rename {demo => docs}/examples/src/appkit/actions/wallets/watch-connected-wallets.ts (100%) rename {demo => docs}/examples/src/appkit/actions/wallets/watch-selected-wallet.ts (100%) rename {demo => docs}/examples/src/appkit/components/balances/balances.test.tsx (100%) rename {demo => docs}/examples/src/appkit/components/balances/send-jetton-button.tsx (100%) rename {demo => docs}/examples/src/appkit/components/balances/send-ton-button.tsx (100%) create mode 100644 docs/examples/src/appkit/components/crypto-onramp/crypto-onramp-widget.tsx create mode 100644 docs/examples/src/appkit/components/crypto-onramp/crypto-onramp.test.tsx create mode 100644 docs/examples/src/appkit/components/nfts/nft-item.tsx create mode 100644 docs/examples/src/appkit/components/nfts/nfts.test.tsx rename {demo => docs}/examples/src/appkit/components/providers/app-kit-provider.tsx (97%) create mode 100644 docs/examples/src/appkit/components/providers/i18n-provider.tsx create mode 100644 docs/examples/src/appkit/components/providers/providers.test.tsx create mode 100644 docs/examples/src/appkit/components/shared/amount-presets.tsx create mode 100644 docs/examples/src/appkit/components/shared/copy-button.tsx create mode 100644 docs/examples/src/appkit/components/shared/currency-item.tsx create mode 100644 docs/examples/src/appkit/components/shared/low-balance-modal.tsx create mode 100644 docs/examples/src/appkit/components/shared/option-switcher.tsx create mode 100644 docs/examples/src/appkit/components/shared/settings-button.tsx create mode 100644 docs/examples/src/appkit/components/shared/shared.test.tsx create mode 100644 docs/examples/src/appkit/components/shared/token-select-modal.tsx create mode 100644 docs/examples/src/appkit/components/shared/token-selector.tsx create mode 100644 docs/examples/src/appkit/components/staking/select-unstake-mode.tsx create mode 100644 docs/examples/src/appkit/components/staking/staking-balance-block.tsx create mode 100644 docs/examples/src/appkit/components/staking/staking-settings-modal.tsx create mode 100644 docs/examples/src/appkit/components/staking/staking-widget.tsx create mode 100644 docs/examples/src/appkit/components/staking/staking.test.tsx create mode 100644 docs/examples/src/appkit/components/swap/swap-field.tsx create mode 100644 docs/examples/src/appkit/components/swap/swap-flip-button.tsx create mode 100644 docs/examples/src/appkit/components/swap/swap-info.tsx create mode 100644 docs/examples/src/appkit/components/swap/swap-widget.tsx create mode 100644 docs/examples/src/appkit/components/swap/swap.test.tsx rename {demo => docs}/examples/src/appkit/components/transaction/transaction.test.tsx (100%) rename {demo => docs}/examples/src/appkit/components/transaction/transaction.tsx (100%) create mode 100644 docs/examples/src/appkit/components/ui/block.tsx create mode 100644 docs/examples/src/appkit/components/ui/button.tsx create mode 100644 docs/examples/src/appkit/components/ui/centered-amount-input.tsx create mode 100644 docs/examples/src/appkit/components/ui/collapsible.tsx create mode 100644 docs/examples/src/appkit/components/ui/info-block.tsx create mode 100644 docs/examples/src/appkit/components/ui/input.tsx create mode 100644 docs/examples/src/appkit/components/ui/logo-with-network.tsx create mode 100644 docs/examples/src/appkit/components/ui/logo.tsx create mode 100644 docs/examples/src/appkit/components/ui/modal.tsx create mode 100644 docs/examples/src/appkit/components/ui/select.tsx create mode 100644 docs/examples/src/appkit/components/ui/skeleton.tsx create mode 100644 docs/examples/src/appkit/components/ui/tabs.tsx create mode 100644 docs/examples/src/appkit/components/ui/ui.test.tsx rename {demo => docs}/examples/src/appkit/components/wallets/connect-button.tsx (100%) rename {demo => docs}/examples/src/appkit/connectors/tonconnect/connector.ts (100%) rename {demo => docs}/examples/src/appkit/hooks/balances/balances.test.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/balances/use-balance-by-address.tsx (92%) rename {demo => docs}/examples/src/appkit/hooks/balances/use-balance.tsx (90%) rename {demo => docs}/examples/src/appkit/hooks/balances/use-watch-balance-by-address.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/balances/use-watch-balance.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/core/use-app-kit-theme.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/core/use-app-kit.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/jettons/jettons.test.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/jettons/use-jetton-balance-by-address.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/jettons/use-jetton-info.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/jettons/use-jetton-wallet-address.tsx (76%) rename {demo => docs}/examples/src/appkit/hooks/jettons/use-jettons-by-address.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/jettons/use-jettons.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/jettons/use-transfer-jetton.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/jettons/use-watch-jettons-by-address.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/jettons/use-watch-jettons.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/network/networks.test.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/network/use-block-number.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/network/use-default-network.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/network/use-network.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/network/use-networks.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/nft/nfts.test.tsx (93%) rename {demo => docs}/examples/src/appkit/hooks/nft/use-nft.tsx (93%) rename {demo => docs}/examples/src/appkit/hooks/nft/use-nfts-by-address.tsx (94%) rename {demo => docs}/examples/src/appkit/hooks/nft/use-nfts.tsx (93%) rename {demo => docs}/examples/src/appkit/hooks/nft/use-transfer-nft.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/onramp/use-crypto-onramp-provider.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/onramp/use-crypto-onramp-providers.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/signing/signing.test.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/signing/use-sign-binary.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/signing/use-sign-cell.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/signing/use-sign-text.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/staking/staking.test.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/staking/use-build-stake-transaction.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/staking/use-staked-balance.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/staking/use-staking-provider-info.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/staking/use-staking-provider-metadata.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/staking/use-staking-provider.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/staking/use-staking-providers.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/staking/use-staking-quote.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/swap/swap.test.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/swap/use-build-swap-transaction.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/swap/use-swap-provider.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/swap/use-swap-providers.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/swap/use-swap-quote.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/transaction/transaction.test.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/transaction/use-send-transaction.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/transaction/use-transfer-ton.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/transaction/use-watch-transactions-by-address.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/transaction/use-watch-transactions.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/wallets/use-address.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/wallets/use-connect.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/wallets/use-connected-wallets.tsx (97%) rename {demo => docs}/examples/src/appkit/hooks/wallets/use-connector-by-id.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/wallets/use-connectors.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/wallets/use-disconnect.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/wallets/use-selected-wallet.tsx (100%) rename {demo => docs}/examples/src/appkit/hooks/wallets/wallets.test.tsx (100%) rename {demo => docs}/examples/src/appkit/setup-react.tsx (100%) rename {demo => docs}/examples/src/appkit/setup.ts (100%) create mode 100644 docs/examples/src/appkit/staking/staking-providers.test.ts rename {demo => docs}/examples/src/appkit/staking/staking-widget.tsx (100%) rename {demo => docs}/examples/src/appkit/staking/tonstakers.ts (100%) rename {demo => docs}/examples/src/appkit/swap/dedust.ts (100%) rename {demo => docs}/examples/src/appkit/swap/omniston.ts (100%) create mode 100644 docs/examples/src/appkit/swap/swap-providers.test.ts rename {demo => docs}/examples/src/appkit/swap/swap-widget.tsx (100%) rename {demo => docs}/examples/src/initialize.ts (100%) rename {demo => docs}/examples/src/jettons.ts (100%) rename {demo => docs}/examples/src/lib/wallet-kit-initialize-sample.ts (100%) rename {demo => docs}/examples/src/lib/wallet-manifest.ts (100%) rename {demo => docs}/examples/src/requests.ts (99%) rename {demo => docs}/examples/src/send-jettons.ts (100%) rename {demo => docs}/examples/src/send-nft.ts (100%) rename {demo => docs}/examples/src/send-ton.ts (100%) rename {demo => docs}/examples/src/ui-state-wiring.ts (100%) rename {demo => docs}/examples/src/ui/render-connect-preview.tsx (100%) rename {demo => docs}/examples/src/ui/render-money-flow.tsx (100%) rename {demo => docs}/examples/src/ui/render-sign-data-preview.tsx (100%) rename {demo => docs}/examples/src/ui/summarize-transaction.tsx (100%) rename {demo => docs}/examples/tsconfig.json (100%) rename {demo => docs}/examples/vitest.config.ts (100%) create mode 100644 docs/reference-generator/package.json create mode 100644 docs/reference-generator/src/collect.ts create mode 100644 docs/reference-generator/src/extract.ts create mode 100644 docs/reference-generator/src/index.ts create mode 100644 docs/reference-generator/src/render.ts create mode 100644 docs/reference-generator/tsconfig.json create mode 100644 docs/template-resolver/package.json rename {scripts => docs/template-resolver/src}/extract-samples.ts (100%) rename scripts/update-docs.ts => docs/template-resolver/src/index.ts (90%) create mode 100644 docs/template-resolver/tsconfig.json rename {template => docs/templates}/packages/appkit-react/README.md (91%) rename {template => docs/templates}/packages/appkit-react/docs/components.md (69%) rename {template => docs/templates}/packages/appkit-react/docs/hooks.md (61%) create mode 100644 docs/templates/packages/appkit-react/docs/reference.md rename {template => docs/templates}/packages/appkit/README.md (93%) rename {template => docs/templates}/packages/appkit/docs/actions.md (60%) rename {template => docs/templates}/packages/appkit/docs/connectors.md (89%) create mode 100644 docs/templates/packages/appkit/docs/reference.md rename {template => docs/templates}/packages/appkit/docs/staking.md (86%) rename {template => docs/templates}/packages/appkit/docs/swap.md (91%) rename {template => docs/templates}/packages/walletkit/README.md (93%) rename {template => docs/templates}/packages/walletkit/src/defi/crypto-onramp/README.md (100%) rename {template => docs/templates}/packages/walletkit/src/defi/crypto-onramp/layerswap/README.md (100%) rename {template => docs/templates}/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/README.md (100%) rename {template => docs/templates}/packages/walletkit/src/defi/staking/README.md (97%) rename {template => docs/templates}/packages/walletkit/src/defi/staking/tonstakers/README.md (90%) rename {template => docs/templates}/packages/walletkit/src/defi/swap/README.md (100%) rename {template => docs/templates}/packages/walletkit/src/defi/swap/dedust/README.md (87%) rename {template => docs/templates}/packages/walletkit/src/defi/swap/omniston/README.md (83%) create mode 100644 packages/appkit-react/docs/reference.md create mode 100644 packages/appkit/docs/reference.md create mode 100644 packages/appkit/src/core/network/walletkit.ts rename packages/appkit/src/types/{balance.ts => api-client.ts} (65%) create mode 100644 packages/appkit/src/types/client.ts diff --git a/.claude/skills/add-action-and-hook/SKILL.md b/.claude/skills/add-action-and-hook/SKILL.md index 316eb3f3e..f1768b2cf 100644 --- a/.claude/skills/add-action-and-hook/SKILL.md +++ b/.claude/skills/add-action-and-hook/SKILL.md @@ -61,6 +61,10 @@ export { } from './/get-xxx'; ``` +### 1.4 Document the action + +Add `@public` JSDoc to the action and to `GetXxxOptions` so they show up in the auto-generated reference. Follow the [`document-public-api`](../document-public-api/SKILL.md) skill for the exact tag set, allowed `@category` values, and style rules (one-sentence summaries, `{@link X}` syntax for type cells, `@expand` for options-bag flattening, `@sample` for code examples). + --- ## Step 2: Create the Query or Mutation in `appkit` (for get actions only) @@ -219,12 +223,16 @@ Add to `packages/appkit-react/src/features//index.ts`: export { useXxx, type UseXxxParameters, type UseXxxReturnType } from './hooks/use-xxx'; ``` +### Document the hook + +Tag the hook (and `UseXxxParameters` / `UseXxxReturnType` if useful) with `@public` JSDoc. Use `@category Hook` and `@section `. The full ruleset (required tags, allowed values, `{@link}` linking, `@sample` placeholders) is in the [`document-public-api`](../document-public-api/SKILL.md) skill. + --- ## Step 4: Add Examples and Tests ### 4.1 Action example -Create `demo/examples/src/appkit/actions//get-xxx.ts`: +Create `docs/examples/src/appkit/actions//get-xxx.ts`: ```ts import type { AppKit } from '@ton/appkit'; import { getXxx } from '@ton/appkit'; @@ -237,10 +245,12 @@ export const getXxxExample = async (appKit: AppKit) => { }; ``` -Export it in `demo/examples/src/appkit/actions//index.ts`. +Export it in `docs/examples/src/appkit/actions//index.ts`. + +The `// SAMPLE_START: GET_XXX … // SAMPLE_END: GET_XXX` block is what `@sample docs/examples/src/appkit/actions/#GET_XXX` in the action's JSDoc will pull into the reference (see [`document-public-api`](../document-public-api/SKILL.md)). ### 4.2 Hook example -Create `demo/examples/src/appkit/hooks//use-xxx.tsx`: +Create `docs/examples/src/appkit/hooks//use-xxx.tsx`: ```tsx import { useXxx } from '@ton/appkit-react'; @@ -252,7 +262,7 @@ export const UseXxxExample = () => { }; ``` -Export it in `demo/examples/src/appkit/hooks//index.ts`. +Export it in `docs/examples/src/appkit/hooks//index.ts`. ### 4.3 Write tests **Important:** Do NOT create a new test file per example. Add tests to the existing `.test.ts` / `.test.tsx` file in the same directory. @@ -280,24 +290,26 @@ If the mock `appKit` in `beforeEach` doesn't have the required mocks (e.g., `get ## Step 5: Update Templates and Docs -### 5.1 Update action template -Edit `template/appkit-actions.md`, add after the nearest related action: +The reference at `packages//docs/reference.md` is fully generated from `@public` JSDoc, so once Step 1.4 / Step 3.1 are done your action and hook are already in the reference. The two steps below update the older hand-curated `actions.md` / `hooks.md` listings. + +### 5.1 Update action listing +Edit `docs/templates/packages/appkit/docs/actions.md`, add after the nearest related action: ```md ### `getXxx` Description of what the action does. -%%demo/examples/src/appkit/actions/#GET_XXX%% +%%docs/examples/src/appkit/actions/#GET_XXX%% ``` -### 5.2 Update hooks template -Edit `template/appkit-hooks.md`, add after the nearest related hook: +### 5.2 Update hooks listing +Edit `docs/templates/packages/appkit-react/docs/hooks.md`, add after the nearest related hook: ```md ### `useXxx` Hook to ... -%%demo/examples/src/appkit/hooks/#USE_XXX%% +%%docs/examples/src/appkit/hooks/#USE_XXX%% ``` ### 5.3 Run quality check @@ -310,4 +322,4 @@ All tests and type checks must pass before continuing. ```bash pnpm docs:update ``` -Verify the relevant `.md` files in `packages/appkit/docs/` and `packages/appkit-react/docs/` were updated. +Runs `docs:reference` (regenerates `reference.md` from `@public` JSDoc) followed by `docs:template` (resolves `%%path#SAMPLE%%` placeholders into real code blocks). Verify the resulting `.md` files in `packages/appkit/docs/` and `packages/appkit-react/docs/` were updated. diff --git a/.claude/skills/add-ui-component/SKILL.md b/.claude/skills/add-ui-component/SKILL.md index 99f9bc0f6..0ee5963c1 100644 --- a/.claude/skills/add-ui-component/SKILL.md +++ b/.claude/skills/add-ui-component/SKILL.md @@ -89,3 +89,13 @@ Use `packages/appkit-react/src/components/block` as the canonical reference for: - `block.tsx` - `block.module.css` - `block.stories.tsx` + +--- + +## 5. Documentation + +If the component is meant to be part of the public API, tag it with `@public` JSDoc so it shows up in the auto-generated reference (`packages/appkit-react/docs/reference.md`). Use `@category Component` and `@section `. The full ruleset (required tags, allowed values, `{@link X}` for type-cell links, single-sentence description style, `@sample` for usage examples) lives in the [`document-public-api`](../document-public-api/SKILL.md) skill. + +For compound components (`const Foo = { Container: …, Item: … }`), the same `@public` block on the namespace object is enough — the generator walks each member and renders them as `#### Foo.Container`, `#### Foo.Item`, etc. + +After editing JSDoc run `pnpm docs:update` to regenerate `packages/appkit-react/docs/reference.md`. diff --git a/.claude/skills/document-public-api/SKILL.md b/.claude/skills/document-public-api/SKILL.md new file mode 100644 index 000000000..3100ad876 --- /dev/null +++ b/.claude/skills/document-public-api/SKILL.md @@ -0,0 +1,224 @@ +--- +name: document-public-api +description: How to write JSDoc for public symbols so they appear in the auto-generated reference (`packages//docs/reference.md`). Use whenever adding `@public` to an export or editing the surrounding doc-comment. +--- + +# Documenting public API for the reference generator + +The generator at `docs/reference-generator/` walks every export of `packages/appkit` and `packages/appkit-react`, picks the ones tagged `@public`, and renders them into `packages//docs/reference.md`. The output goes through `docs/template-resolver/` which resolves `%%path#NAME%%` placeholders into real code from `docs/examples/`. + +This skill describes exactly which JSDoc tags the generator understands, in what shape, and what the rendered output looks like. + +--- + +## Required tags + +Every `@public` symbol **must** also declare: + +- `@public` — opt-in marker. Without it the symbol is invisible to the generator. +- `@category ` — top-level group (`## Class`, `## Action`, …). The generator validates the value; anything else is an error. +- `@section ` — second-level group (`### Balances`, `### Connectors and wallets`, …). Free-form string; symbols sharing the same value end up under one heading. + +If any of the three is missing, `pnpm docs:reference` aborts with a list of offending symbols. + +### Which declaration shape fits each `@category` + +| `@category` | Allowed declaration | +| --- | --- | +| `Class` | `export class X { }` | +| `Action` / `Hook` | `export function name(...)` or `export const name = (...) => ...` | +| `Component` | Function returning JSX **or** a `const X = { Sub: …, Sub2: … }` object of FCs (rendered as a compound component) | +| `Type` | `export interface X { }` or `export type X = ...` | +| `Constants` | `export const X = { ... } as const` (or any `export const X = literal`) | + +Putting `@category Class` on an interface raises `[X] @category Class requires the symbol to be a class declaration.` at generate time. `Type` and `Constants` are deliberately split so a `const X = {}` cannot accidentally land under "Type" — pick `Constants` for runtime values, `Type` for compile-time-only declarations. + +--- + +## Optional tags + +- `@param - ` — column row in the parameters table. Description should be a single self-contained sentence with a trailing period. +- `@returns ` — appears as `Returns: \`Type\` — .` +- `@example` — inline TS/TSX code block printed under the entry. +- `@sample #` — placeholder that `pnpm docs:template` replaces with the body of a `// SAMPLE_START: NAME … // SAMPLE_END: NAME` block under `docs/examples/`. Multiple `@sample` tags are allowed. +- `@expand ` — for actions that take an options-bag (`getBalanceByAddress(appKit, options)`), expands the named parameter's fields into extra rows like `options.address`, `options.network`. Without `@expand`, the parameter is shown as one row. +- `@extract` — for type aliases that re-export a type from another package (typically walletkit). The renderer follows the alias to the original `interface` / `type` and uses **its** structure (field table or code block). `@public`/`@category`/`@section` still live on the alias; the source's JSDoc supplies field-level descriptions. See "Re-exporting from walletkit" below. +- `@title ` — override the top-level heading for this single symbol. Rarely needed; usually omit. + +`@param` accepts a `{@link X}`-as-type-override at the very start of its description (see below); `@returns` does **not** — see the warning in that section. + +--- + +## Cross-reference syntax: `{@link X}` + +`{@link X}` becomes a markdown link to the `#x` anchor in the same reference. It works in two places: + +1. **Anywhere in a description** (summary, field doc, `@param` description, `@returns` description). The text reads `... see {@link getBalance} ...` and renders `... see [\`getBalance\`](#getbalance) ...`. + +2. **At the very start of `@param` description** — the link is extracted and used as the **Type column** for that row. The text after the link goes into the Description column. + + ```ts + @param config - {@link AppKitConfig} Networks, connectors, providers and runtime flags. + ``` + + renders as: + + | Parameter | Type | Description | + | --- | --- | --- | + | `config`* | [`AppKitConfig`](#appkitconfig) | Networks, connectors, providers and runtime flags. | + + The TS-inferred type is replaced by the link. Use this when the inferred type is verbose or you want a cleaner cell. + + ⚠ **Don't put `{@link X}` at the start of `@returns`.** ts-morph's JSDoc parser interprets a leading `{…}` as a legacy type annotation (`@returns {Type} desc`) and silently drops it from the comment text — both the type-override and the description disappear. Write the description as plain prose; the inferred return type is auto-linked anyway. If you really want to mention a type, put `{@link X}` mid-sentence: `@returns The wallet response carrying …`. + +`X` must name another `@public` symbol in the same reference — the generator does not validate this, so a typo or an undocumented target produces a dead link. + +--- + +## Style rules + +- **One sentence per description.** Summary, `@param` description, field doc, `@returns` description — all collapse onto one line in the rendered table. Multi-paragraph JSDoc reads as a long ugly run-on. If you need a second clause, join with `;` or `—`. +- **Self-contained sentences after `{@link X}`.** Capitalize the first word, end with a period. Don't write `{@link X} with foo` (renders as Description = `with foo` — fragment); write `{@link X} Foo and bar.`. +- **No bullet lists, no fenced code, no tables in JSDoc descriptions.** They survive the markdown but break table rendering. +- **No outright fabrication.** Don't claim methods or behavior that don't exist in the code; the reference is pulled directly from the JSDoc and any error there ships to readers. + +--- + +## Worked example + +```ts +/** + * Read the Toncoin balance of an arbitrary address — useful for wallets that aren't selected in AppKit (use {@link getBalance} for the selected wallet). + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetBalanceByAddressOptions} Target address and optional network. + * @returns Balance in TON as a human-readable decimal string. + * + * @sample docs/examples/src/appkit/actions/balances#GET_BALANCE_BY_ADDRESS + * @expand options + * + * @public + * @category Action + * @section Balances + */ +export const getBalanceByAddress = async ( + appKit: AppKit, + options: GetBalanceByAddressOptions, +): Promise => { /* ... */ }; +``` + +```ts +/** + * Constructor options for {@link AppKit} — networks, connectors, providers and runtime flags. + * + * @public + * @category Type + * @section Core + */ +export interface AppKitConfig { + /** Map of chain id to api-client config; if omitted, AppKit defaults to mainnet only. */ + networks?: NetworkAdapters; + + /** Wallet connectors registered at startup. */ + connectors?: ConnectorInput[]; + + /** Default network connectors enforce on new connections; `undefined` to allow any. */ + defaultNetwork?: Network; + + /** Defi/onramp providers registered at startup. */ + providers?: ProviderInput[]; +} +``` + +--- + +## Re-exporting from walletkit (`@extract`) + +Some types live in `@ton/walletkit` but are part of the `@ton/appkit` public API (e.g. `Network`, `NetworkAdapters`, `NetworkConfig`, `ApiClientConfig`). A bare `export { Network } from '@ton/walletkit'` will **not** appear in the appkit reference — `collect.ts` filters out symbols whose declaration lives outside the package. Use a local type alias plus `@extract` to surface them: + +```ts +// packages/appkit/src/types/network.ts +import type { NetworkAdapters as WalletkitNetworkAdapters } from '@ton/walletkit'; + +/** + * @extract + * @public + * @category Type + * @section Networks + */ +export type NetworkAdapters = WalletkitNetworkAdapters; +``` + +What happens at generate time: + +1. The alias declaration sits in `appkit/src/`, so the package-boundary filter passes it. +2. `@extract` tells `extractType` to follow the alias to the underlying walletkit `interface`/`type` and reuse its shape — fields show up in the reference table, JSDoc on each field is pulled from walletkit. +3. `@public`/`@category`/`@section` are read from the alias (you control where it appears in the appkit reference, not walletkit). +4. If the alias has its own summary on the JSDoc block, that takes precedence over walletkit's. + +For declaration-merged symbols (a value + same-named interface, like `Network`), keep the value side as a separate `export const`: + +```ts +import type { Network as WalletkitNetwork } from '@ton/walletkit'; +import { Network as WalletkitNetworkValue } from '@ton/walletkit'; + +/** + * @extract + * @public + * @category Type + * @section Networks + */ +export type Network = WalletkitNetwork; + +// Value side — `Network.mainnet()` etc. +export const Network = WalletkitNetworkValue; +``` + +The cleanest form is a JSDoc-tagged ExportDeclaration — one block tags every symbol inside the same `export { … }`: + +```ts +/** + * @extract + * @public + * @category Class + * @section Swap + */ +export { SwapError, SwapProvider, SwapManager } from '@ton/walletkit'; + +/** + * @extract + * @public + * @category Type + * @section Swap + */ +export type { SwapToken, TokenAmount, SwapParams } from '@ton/walletkit'; +``` + +Group symbols by `(category, section)` — one ExportDeclaration per group keeps the JSDoc shared. + +**Rebuild walletkit after editing its JSDoc.** ts-morph resolves cross-package symbols through `dist/.../*.d.ts`, not the source `*.ts`, so JSDoc edits in `packages/walletkit/src/...` only land in the reference after `pnpm --filter @ton/walletkit build`. For appkit-only edits (no walletkit changes), `pnpm docs:update` alone is enough. + +**Important**: `@extract` does NOT make a wildcard `export * from '@ton/appkit'` (used in appkit-react) leak appkit symbols into appkit-react. Wildcard re-exports cannot carry JSDoc, so they cannot carry `@extract`, so the boundary filter still drops them. The opt-in is local and explicit. + +--- + +## After editing JSDoc + +Run `pnpm docs:update` (alias for `pnpm docs:reference && pnpm docs:template`). The first step regenerates `docs/templates/packages//docs/reference.md`; the second resolves `@sample` placeholders into real code blocks and writes the final `packages//docs/reference.md`. + +If validation fails, the script prints every problem in one go — fix them all before re-running. + +--- + +## Quick checklist + +- [ ] `@public` present +- [ ] `@category` set to one of `Class`, `Action`, `Hook`, `Component`, `Type`, `Constants` +- [ ] `@section` set to a domain string (matches existing entries where appropriate) +- [ ] Summary is one sentence with a trailing period +- [ ] Each `@param` description is one self-contained sentence +- [ ] `{@link X}` only used for symbols that are themselves `@public` +- [ ] `@expand` used for any options-bag parameter you want flattened +- [ ] `@extract` used for type aliases that re-export a walletkit type +- [ ] `@sample` points to a real `// SAMPLE_START: NAME` block in `docs/examples/` +- [ ] `pnpm docs:update` runs cleanly diff --git a/demo/examples/.gitignore b/docs/examples/.gitignore similarity index 100% rename from demo/examples/.gitignore rename to docs/examples/.gitignore diff --git a/demo/examples/env.d.ts b/docs/examples/env.d.ts similarity index 100% rename from demo/examples/env.d.ts rename to docs/examples/env.d.ts diff --git a/demo/examples/index.html b/docs/examples/index.html similarity index 100% rename from demo/examples/index.html rename to docs/examples/index.html diff --git a/demo/examples/package.json b/docs/examples/package.json similarity index 100% rename from demo/examples/package.json rename to docs/examples/package.json diff --git a/demo/examples/src/__mocks__/@ton/walletkit.ts b/docs/examples/src/__mocks__/@ton/walletkit.ts similarity index 100% rename from demo/examples/src/__mocks__/@ton/walletkit.ts rename to docs/examples/src/__mocks__/@ton/walletkit.ts diff --git a/demo/examples/src/__mocks__/@tonconnect/sdk.ts b/docs/examples/src/__mocks__/@tonconnect/sdk.ts similarity index 100% rename from demo/examples/src/__mocks__/@tonconnect/sdk.ts rename to docs/examples/src/__mocks__/@tonconnect/sdk.ts diff --git a/demo/examples/src/__mocks__/@tonconnect/ui-react.ts b/docs/examples/src/__mocks__/@tonconnect/ui-react.ts similarity index 100% rename from demo/examples/src/__mocks__/@tonconnect/ui-react.ts rename to docs/examples/src/__mocks__/@tonconnect/ui-react.ts diff --git a/demo/examples/src/__tests__/initialize.test.ts b/docs/examples/src/__tests__/initialize.test.ts similarity index 100% rename from demo/examples/src/__tests__/initialize.test.ts rename to docs/examples/src/__tests__/initialize.test.ts diff --git a/demo/examples/src/__tests__/jettons.test.ts b/docs/examples/src/__tests__/jettons.test.ts similarity index 100% rename from demo/examples/src/__tests__/jettons.test.ts rename to docs/examples/src/__tests__/jettons.test.ts diff --git a/demo/examples/src/__tests__/requests.test.ts b/docs/examples/src/__tests__/requests.test.ts similarity index 100% rename from demo/examples/src/__tests__/requests.test.ts rename to docs/examples/src/__tests__/requests.test.ts diff --git a/demo/examples/src/__tests__/setup.ts b/docs/examples/src/__tests__/setup.ts similarity index 100% rename from demo/examples/src/__tests__/setup.ts rename to docs/examples/src/__tests__/setup.ts diff --git a/demo/examples/src/__tests__/test-utils.tsx b/docs/examples/src/__tests__/test-utils.tsx similarity index 100% rename from demo/examples/src/__tests__/test-utils.tsx rename to docs/examples/src/__tests__/test-utils.tsx diff --git a/demo/examples/src/__tests__/transfers.test.ts b/docs/examples/src/__tests__/transfers.test.ts similarity index 100% rename from demo/examples/src/__tests__/transfers.test.ts rename to docs/examples/src/__tests__/transfers.test.ts diff --git a/demo/examples/src/__tests__/ui-state-wiring.test.ts b/docs/examples/src/__tests__/ui-state-wiring.test.ts similarity index 100% rename from demo/examples/src/__tests__/ui-state-wiring.test.ts rename to docs/examples/src/__tests__/ui-state-wiring.test.ts diff --git a/demo/examples/src/__tests__/ui.test.ts b/docs/examples/src/__tests__/ui.test.ts similarity index 100% rename from demo/examples/src/__tests__/ui.test.ts rename to docs/examples/src/__tests__/ui.test.ts diff --git a/demo/examples/src/__tests__/wallet-kit-initialize-sample.test.ts b/docs/examples/src/__tests__/wallet-kit-initialize-sample.test.ts similarity index 100% rename from demo/examples/src/__tests__/wallet-kit-initialize-sample.test.ts rename to docs/examples/src/__tests__/wallet-kit-initialize-sample.test.ts diff --git a/demo/examples/src/appkit/actions/balances/balances.test.ts b/docs/examples/src/appkit/actions/balances/balances.test.ts similarity index 92% rename from demo/examples/src/appkit/actions/balances/balances.test.ts rename to docs/examples/src/appkit/actions/balances/balances.test.ts index 625e0a859..08932e82a 100644 --- a/demo/examples/src/appkit/actions/balances/balances.test.ts +++ b/docs/examples/src/appkit/actions/balances/balances.test.ts @@ -63,11 +63,8 @@ describe('Balance Actions Examples (Integration)', () => { appKit.walletsManager.setWallets([mockWallet]); - // Setup balance response - // Using a simple object that mimics TokenAmount to avoid constructor issues if any, - // or we could use `new TokenAmount(1000000000n, 9)` if available. - // Since we test the example which calls .toString(), this is sufficient. - const balanceValue = { toString: () => '1000000000' } as TokenAmount; + // Setup balance response. TokenAmount is a string alias. + const balanceValue: TokenAmount = '1000000000'; mockGetBalance.mockResolvedValue(balanceValue); await getBalanceExample(appKit); diff --git a/demo/examples/src/appkit/actions/balances/get-balance-by-address.ts b/docs/examples/src/appkit/actions/balances/get-balance-by-address.ts similarity index 86% rename from demo/examples/src/appkit/actions/balances/get-balance-by-address.ts rename to docs/examples/src/appkit/actions/balances/get-balance-by-address.ts index 972f71e84..eb08ec524 100644 --- a/demo/examples/src/appkit/actions/balances/get-balance-by-address.ts +++ b/docs/examples/src/appkit/actions/balances/get-balance-by-address.ts @@ -12,8 +12,8 @@ import { getBalanceByAddress } from '@ton/appkit'; export const getBalanceByAddressExample = async (appKit: AppKit) => { // SAMPLE_START: GET_BALANCE_BY_ADDRESS const balanceByAddress = await getBalanceByAddress(appKit, { - address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', // Zero Address + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', }); - console.log('Balance by address:', balanceByAddress.toString()); + console.log('Balance by address:', balanceByAddress); // SAMPLE_END: GET_BALANCE_BY_ADDRESS }; diff --git a/demo/examples/src/appkit/actions/balances/get-balance.ts b/docs/examples/src/appkit/actions/balances/get-balance.ts similarity index 89% rename from demo/examples/src/appkit/actions/balances/get-balance.ts rename to docs/examples/src/appkit/actions/balances/get-balance.ts index 418c85f36..ed4ff847e 100644 --- a/demo/examples/src/appkit/actions/balances/get-balance.ts +++ b/docs/examples/src/appkit/actions/balances/get-balance.ts @@ -13,7 +13,7 @@ export const getBalanceExample = async (appKit: AppKit) => { // SAMPLE_START: GET_BALANCE const balance = await getBalance(appKit); if (balance) { - console.log('Balance:', balance.toString()); + console.log('Balance:', balance); } // SAMPLE_END: GET_BALANCE }; diff --git a/demo/examples/src/appkit/actions/balances/watch-balance-by-address.ts b/docs/examples/src/appkit/actions/balances/watch-balance-by-address.ts similarity index 100% rename from demo/examples/src/appkit/actions/balances/watch-balance-by-address.ts rename to docs/examples/src/appkit/actions/balances/watch-balance-by-address.ts diff --git a/demo/examples/src/appkit/actions/balances/watch-balance.ts b/docs/examples/src/appkit/actions/balances/watch-balance.ts similarity index 100% rename from demo/examples/src/appkit/actions/balances/watch-balance.ts rename to docs/examples/src/appkit/actions/balances/watch-balance.ts diff --git a/demo/examples/src/appkit/actions/connectors/add-connector.ts b/docs/examples/src/appkit/actions/connectors/add-connector.ts similarity index 87% rename from demo/examples/src/appkit/actions/connectors/add-connector.ts rename to docs/examples/src/appkit/actions/connectors/add-connector.ts index 5318c3e51..9d76c9ec1 100644 --- a/demo/examples/src/appkit/actions/connectors/add-connector.ts +++ b/docs/examples/src/appkit/actions/connectors/add-connector.ts @@ -12,7 +12,7 @@ import { createTonConnectConnector } from '@ton/appkit'; export const addConnectorExample = (appKit: AppKit) => { // SAMPLE_START: ADD_CONNECTOR - const stopWatching = addConnector( + const unregister = addConnector( appKit, createTonConnectConnector({ tonConnectOptions: { @@ -21,7 +21,7 @@ export const addConnectorExample = (appKit: AppKit) => { }), ); - // Later: stopWatching(); + // Later: unregister(); // SAMPLE_END: ADD_CONNECTOR - return stopWatching; + return unregister; }; diff --git a/demo/examples/src/appkit/actions/connectors/connect.ts b/docs/examples/src/appkit/actions/connectors/connect.ts similarity index 100% rename from demo/examples/src/appkit/actions/connectors/connect.ts rename to docs/examples/src/appkit/actions/connectors/connect.ts diff --git a/demo/examples/src/appkit/actions/connectors/connectors.test.ts b/docs/examples/src/appkit/actions/connectors/connectors.test.ts similarity index 90% rename from demo/examples/src/appkit/actions/connectors/connectors.test.ts rename to docs/examples/src/appkit/actions/connectors/connectors.test.ts index dfcbdab81..1240ae912 100644 --- a/demo/examples/src/appkit/actions/connectors/connectors.test.ts +++ b/docs/examples/src/appkit/actions/connectors/connectors.test.ts @@ -94,13 +94,7 @@ describe('Connector Actions Examples (Integration)', () => { watchConnectorsExample(appKit); // Trigger event - appKit.emitter.emit( - CONNECTOR_EVENTS.ADDED, - { - connector: mockConnector, - }, - 'test', - ); + appKit.emitter.emit(CONNECTOR_EVENTS.ADDED, { connector: mockConnector }, 'test'); expect(consoleSpy).toHaveBeenCalledWith('Connectors updated:', expect.arrayContaining([mockConnector])); }); @@ -111,13 +105,7 @@ describe('Connector Actions Examples (Integration)', () => { watchConnectorByIdExample(appKit); // Trigger event - appKit.emitter.emit( - CONNECTOR_EVENTS.ADDED, - { - connector: mockConnector, - }, - 'test', - ); + appKit.emitter.emit(CONNECTOR_EVENTS.ADDED, { connector: mockConnector }, 'test'); expect(consoleSpy).toHaveBeenCalledWith('Connector updated:', mockConnector); }); diff --git a/demo/examples/src/appkit/actions/connectors/disconnect.ts b/docs/examples/src/appkit/actions/connectors/disconnect.ts similarity index 100% rename from demo/examples/src/appkit/actions/connectors/disconnect.ts rename to docs/examples/src/appkit/actions/connectors/disconnect.ts diff --git a/demo/examples/src/appkit/actions/connectors/get-connector-by-id.ts b/docs/examples/src/appkit/actions/connectors/get-connector-by-id.ts similarity index 100% rename from demo/examples/src/appkit/actions/connectors/get-connector-by-id.ts rename to docs/examples/src/appkit/actions/connectors/get-connector-by-id.ts diff --git a/demo/examples/src/appkit/actions/connectors/get-connectors.ts b/docs/examples/src/appkit/actions/connectors/get-connectors.ts similarity index 100% rename from demo/examples/src/appkit/actions/connectors/get-connectors.ts rename to docs/examples/src/appkit/actions/connectors/get-connectors.ts diff --git a/demo/examples/src/appkit/actions/connectors/watch-connector-by-id.ts b/docs/examples/src/appkit/actions/connectors/watch-connector-by-id.ts similarity index 100% rename from demo/examples/src/appkit/actions/connectors/watch-connector-by-id.ts rename to docs/examples/src/appkit/actions/connectors/watch-connector-by-id.ts diff --git a/demo/examples/src/appkit/actions/connectors/watch-connectors.ts b/docs/examples/src/appkit/actions/connectors/watch-connectors.ts similarity index 100% rename from demo/examples/src/appkit/actions/connectors/watch-connectors.ts rename to docs/examples/src/appkit/actions/connectors/watch-connectors.ts diff --git a/demo/examples/src/appkit/actions/jettons/create-transfer-jetton-transaction.ts b/docs/examples/src/appkit/actions/jettons/create-transfer-jetton-transaction.ts similarity index 100% rename from demo/examples/src/appkit/actions/jettons/create-transfer-jetton-transaction.ts rename to docs/examples/src/appkit/actions/jettons/create-transfer-jetton-transaction.ts diff --git a/demo/examples/src/appkit/actions/jettons/get-jetton-balance.ts b/docs/examples/src/appkit/actions/jettons/get-jetton-balance.ts similarity index 93% rename from demo/examples/src/appkit/actions/jettons/get-jetton-balance.ts rename to docs/examples/src/appkit/actions/jettons/get-jetton-balance.ts index 17219d3f6..c45daaec9 100644 --- a/demo/examples/src/appkit/actions/jettons/get-jetton-balance.ts +++ b/docs/examples/src/appkit/actions/jettons/get-jetton-balance.ts @@ -22,6 +22,6 @@ export const getJettonBalanceExample = async (appKit: AppKit) => { ownerAddress: selectedWallet.getAddress(), jettonDecimals: 6, }); - console.log('Jetton Balance:', balance.toString()); + console.log('Jetton Balance:', balance); // SAMPLE_END: GET_JETTON_BALANCE }; diff --git a/demo/examples/src/appkit/actions/jettons/get-jetton-info.ts b/docs/examples/src/appkit/actions/jettons/get-jetton-info.ts similarity index 100% rename from demo/examples/src/appkit/actions/jettons/get-jetton-info.ts rename to docs/examples/src/appkit/actions/jettons/get-jetton-info.ts diff --git a/demo/examples/src/appkit/actions/jettons/get-jetton-wallet-address.ts b/docs/examples/src/appkit/actions/jettons/get-jetton-wallet-address.ts similarity index 100% rename from demo/examples/src/appkit/actions/jettons/get-jetton-wallet-address.ts rename to docs/examples/src/appkit/actions/jettons/get-jetton-wallet-address.ts diff --git a/demo/examples/src/appkit/actions/jettons/get-jettons-by-address.ts b/docs/examples/src/appkit/actions/jettons/get-jettons-by-address.ts similarity index 96% rename from demo/examples/src/appkit/actions/jettons/get-jettons-by-address.ts rename to docs/examples/src/appkit/actions/jettons/get-jettons-by-address.ts index 4367b8b91..516fa322e 100644 --- a/demo/examples/src/appkit/actions/jettons/get-jettons-by-address.ts +++ b/docs/examples/src/appkit/actions/jettons/get-jettons-by-address.ts @@ -21,6 +21,6 @@ export const getJettonsByAddressExample = async (appKit: AppKit) => { address: selectedWallet.getAddress(), }); console.log('Jettons by Address:', response.jettons.length); - response.jettons.forEach((j) => console.log(`- ${j.info.name}: ${j.balance.toString()}`)); + response.jettons.forEach((j) => console.log(`- ${j.info.name}: ${j.balance}`)); // SAMPLE_END: GET_JETTONS_BY_ADDRESS }; diff --git a/demo/examples/src/appkit/actions/jettons/get-jettons.ts b/docs/examples/src/appkit/actions/jettons/get-jettons.ts similarity index 95% rename from demo/examples/src/appkit/actions/jettons/get-jettons.ts rename to docs/examples/src/appkit/actions/jettons/get-jettons.ts index fcd63ac6e..abece18c1 100644 --- a/demo/examples/src/appkit/actions/jettons/get-jettons.ts +++ b/docs/examples/src/appkit/actions/jettons/get-jettons.ts @@ -17,6 +17,6 @@ export const getJettonsExample = async (appKit: AppKit) => { return; } console.log('Jettons:', response.jettons.length); - response.jettons.forEach((j) => console.log(`- ${j.info.name}: ${j.balance.toString()}`)); + response.jettons.forEach((j) => console.log(`- ${j.info.name}: ${j.balance}`)); // SAMPLE_END: GET_JETTONS }; diff --git a/demo/examples/src/appkit/actions/jettons/jettons.test.ts b/docs/examples/src/appkit/actions/jettons/jettons.test.ts similarity index 98% rename from demo/examples/src/appkit/actions/jettons/jettons.test.ts rename to docs/examples/src/appkit/actions/jettons/jettons.test.ts index 60816b075..0714c5f20 100644 --- a/demo/examples/src/appkit/actions/jettons/jettons.test.ts +++ b/docs/examples/src/appkit/actions/jettons/jettons.test.ts @@ -139,10 +139,7 @@ describe('Jetton Actions Examples (Integration)', () => { 'get_wallet_address', expect.any(Array), ); - expect(consoleSpy).toHaveBeenCalledWith( - 'Jetton Wallet Address:', - Address.parse(JETTON_WALLET_ADDRESS).toString(), - ); + expect(consoleSpy).toHaveBeenCalledWith('Jetton Wallet Address:', JETTON_WALLET_ADDRESS); }); it('should log message if no wallet selected', async () => { diff --git a/demo/examples/src/appkit/actions/jettons/transfer-jetton.ts b/docs/examples/src/appkit/actions/jettons/transfer-jetton.ts similarity index 100% rename from demo/examples/src/appkit/actions/jettons/transfer-jetton.ts rename to docs/examples/src/appkit/actions/jettons/transfer-jetton.ts diff --git a/demo/examples/src/appkit/actions/network/get-api-client.ts b/docs/examples/src/appkit/actions/network/get-api-client.ts similarity index 100% rename from demo/examples/src/appkit/actions/network/get-api-client.ts rename to docs/examples/src/appkit/actions/network/get-api-client.ts diff --git a/demo/examples/src/appkit/actions/network/get-block-number.ts b/docs/examples/src/appkit/actions/network/get-block-number.ts similarity index 100% rename from demo/examples/src/appkit/actions/network/get-block-number.ts rename to docs/examples/src/appkit/actions/network/get-block-number.ts diff --git a/demo/examples/src/appkit/actions/network/get-default-network.ts b/docs/examples/src/appkit/actions/network/get-default-network.ts similarity index 100% rename from demo/examples/src/appkit/actions/network/get-default-network.ts rename to docs/examples/src/appkit/actions/network/get-default-network.ts diff --git a/demo/examples/src/appkit/actions/network/get-network.ts b/docs/examples/src/appkit/actions/network/get-network.ts similarity index 100% rename from demo/examples/src/appkit/actions/network/get-network.ts rename to docs/examples/src/appkit/actions/network/get-network.ts diff --git a/demo/examples/src/appkit/actions/network/get-networks.ts b/docs/examples/src/appkit/actions/network/get-networks.ts similarity index 100% rename from demo/examples/src/appkit/actions/network/get-networks.ts rename to docs/examples/src/appkit/actions/network/get-networks.ts diff --git a/demo/examples/src/appkit/actions/network/has-streaming-provider.ts b/docs/examples/src/appkit/actions/network/has-streaming-provider.ts similarity index 100% rename from demo/examples/src/appkit/actions/network/has-streaming-provider.ts rename to docs/examples/src/appkit/actions/network/has-streaming-provider.ts diff --git a/demo/examples/src/appkit/actions/network/network.test.ts b/docs/examples/src/appkit/actions/network/network.test.ts similarity index 100% rename from demo/examples/src/appkit/actions/network/network.test.ts rename to docs/examples/src/appkit/actions/network/network.test.ts diff --git a/demo/examples/src/appkit/actions/network/set-default-network.ts b/docs/examples/src/appkit/actions/network/set-default-network.ts similarity index 100% rename from demo/examples/src/appkit/actions/network/set-default-network.ts rename to docs/examples/src/appkit/actions/network/set-default-network.ts diff --git a/demo/examples/src/appkit/actions/network/watch-default-network.ts b/docs/examples/src/appkit/actions/network/watch-default-network.ts similarity index 100% rename from demo/examples/src/appkit/actions/network/watch-default-network.ts rename to docs/examples/src/appkit/actions/network/watch-default-network.ts diff --git a/demo/examples/src/appkit/actions/network/watch-networks.ts b/docs/examples/src/appkit/actions/network/watch-networks.ts similarity index 100% rename from demo/examples/src/appkit/actions/network/watch-networks.ts rename to docs/examples/src/appkit/actions/network/watch-networks.ts diff --git a/demo/examples/src/appkit/actions/nft/create-transfer-nft-transaction.ts b/docs/examples/src/appkit/actions/nft/create-transfer-nft-transaction.ts similarity index 100% rename from demo/examples/src/appkit/actions/nft/create-transfer-nft-transaction.ts rename to docs/examples/src/appkit/actions/nft/create-transfer-nft-transaction.ts diff --git a/demo/examples/src/appkit/actions/nft/get-nft.ts b/docs/examples/src/appkit/actions/nft/get-nft.ts similarity index 100% rename from demo/examples/src/appkit/actions/nft/get-nft.ts rename to docs/examples/src/appkit/actions/nft/get-nft.ts diff --git a/demo/examples/src/appkit/actions/nft/get-nfts-by-address.ts b/docs/examples/src/appkit/actions/nft/get-nfts-by-address.ts similarity index 96% rename from demo/examples/src/appkit/actions/nft/get-nfts-by-address.ts rename to docs/examples/src/appkit/actions/nft/get-nfts-by-address.ts index 0880e14e3..0283da8f0 100644 --- a/demo/examples/src/appkit/actions/nft/get-nfts-by-address.ts +++ b/docs/examples/src/appkit/actions/nft/get-nfts-by-address.ts @@ -12,7 +12,7 @@ import { getNftsByAddress } from '@ton/appkit'; export const getNftsByAddressExample = async (appKit: AppKit) => { // SAMPLE_START: GET_NFTS_BY_ADDRESS const response = await getNftsByAddress(appKit, { - address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', // Zero Address + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', }); console.log('NFTs by address:', response.nfts.length); diff --git a/demo/examples/src/appkit/actions/nft/get-nfts.ts b/docs/examples/src/appkit/actions/nft/get-nfts.ts similarity index 100% rename from demo/examples/src/appkit/actions/nft/get-nfts.ts rename to docs/examples/src/appkit/actions/nft/get-nfts.ts diff --git a/demo/examples/src/appkit/actions/nft/nfts.test.ts b/docs/examples/src/appkit/actions/nft/nfts.test.ts similarity index 100% rename from demo/examples/src/appkit/actions/nft/nfts.test.ts rename to docs/examples/src/appkit/actions/nft/nfts.test.ts diff --git a/demo/examples/src/appkit/actions/nft/transfer-nft.ts b/docs/examples/src/appkit/actions/nft/transfer-nft.ts similarity index 100% rename from demo/examples/src/appkit/actions/nft/transfer-nft.ts rename to docs/examples/src/appkit/actions/nft/transfer-nft.ts diff --git a/demo/examples/src/appkit/actions/onramp/build-onramp-url.ts b/docs/examples/src/appkit/actions/onramp/build-onramp-url.ts similarity index 100% rename from demo/examples/src/appkit/actions/onramp/build-onramp-url.ts rename to docs/examples/src/appkit/actions/onramp/build-onramp-url.ts diff --git a/demo/examples/src/appkit/actions/onramp/get-crypto-onramp-provider.ts b/docs/examples/src/appkit/actions/onramp/get-crypto-onramp-provider.ts similarity index 100% rename from demo/examples/src/appkit/actions/onramp/get-crypto-onramp-provider.ts rename to docs/examples/src/appkit/actions/onramp/get-crypto-onramp-provider.ts diff --git a/demo/examples/src/appkit/actions/onramp/get-crypto-onramp-providers.ts b/docs/examples/src/appkit/actions/onramp/get-crypto-onramp-providers.ts similarity index 100% rename from demo/examples/src/appkit/actions/onramp/get-crypto-onramp-providers.ts rename to docs/examples/src/appkit/actions/onramp/get-crypto-onramp-providers.ts diff --git a/demo/examples/src/appkit/actions/onramp/get-onramp-quote.ts b/docs/examples/src/appkit/actions/onramp/get-onramp-quote.ts similarity index 100% rename from demo/examples/src/appkit/actions/onramp/get-onramp-quote.ts rename to docs/examples/src/appkit/actions/onramp/get-onramp-quote.ts diff --git a/demo/examples/src/appkit/actions/providers/register-provider.ts b/docs/examples/src/appkit/actions/providers/register-provider.ts similarity index 100% rename from demo/examples/src/appkit/actions/providers/register-provider.ts rename to docs/examples/src/appkit/actions/providers/register-provider.ts diff --git a/demo/examples/src/appkit/actions/signing/sign-binary.ts b/docs/examples/src/appkit/actions/signing/sign-binary.ts similarity index 100% rename from demo/examples/src/appkit/actions/signing/sign-binary.ts rename to docs/examples/src/appkit/actions/signing/sign-binary.ts diff --git a/demo/examples/src/appkit/actions/signing/sign-cell.ts b/docs/examples/src/appkit/actions/signing/sign-cell.ts similarity index 99% rename from demo/examples/src/appkit/actions/signing/sign-cell.ts rename to docs/examples/src/appkit/actions/signing/sign-cell.ts index cae624602..9b1e54f7b 100644 --- a/demo/examples/src/appkit/actions/signing/sign-cell.ts +++ b/docs/examples/src/appkit/actions/signing/sign-cell.ts @@ -12,7 +12,7 @@ import { signCell } from '@ton/appkit'; export const signCellExample = async (appKit: AppKit) => { // SAMPLE_START: SIGN_CELL const result = await signCell(appKit, { - cell: 'te6ccgEBAQEAAgAAGA==' as Base64String, // Example BOC + cell: 'te6ccgEBAQEAAgAAGA==' as Base64String, // Example BoC schema: 'transfer#abc123 amount:uint64 = Transfer', }); diff --git a/demo/examples/src/appkit/actions/signing/sign-text.ts b/docs/examples/src/appkit/actions/signing/sign-text.ts similarity index 100% rename from demo/examples/src/appkit/actions/signing/sign-text.ts rename to docs/examples/src/appkit/actions/signing/sign-text.ts diff --git a/demo/examples/src/appkit/actions/signing/signing.test.ts b/docs/examples/src/appkit/actions/signing/signing.test.ts similarity index 100% rename from demo/examples/src/appkit/actions/signing/signing.test.ts rename to docs/examples/src/appkit/actions/signing/signing.test.ts diff --git a/demo/examples/src/appkit/actions/staking/staking-actions.ts b/docs/examples/src/appkit/actions/staking/staking-actions.ts similarity index 97% rename from demo/examples/src/appkit/actions/staking/staking-actions.ts rename to docs/examples/src/appkit/actions/staking/staking-actions.ts index 6c3d59c1a..774bbdee8 100644 --- a/demo/examples/src/appkit/actions/staking/staking-actions.ts +++ b/docs/examples/src/appkit/actions/staking/staking-actions.ts @@ -20,7 +20,7 @@ export const stakingExample = async (appKit: AppKit) => { const userAddress = 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c'; // SAMPLE_START: GET_STAKING_PROVIDERS - const providers = await getStakingProviders(appKit); + const providers = getStakingProviders(appKit); console.log('Available Staking Providers:', providers); // SAMPLE_END: GET_STAKING_PROVIDERS diff --git a/demo/examples/src/appkit/actions/staking/staking.test.ts b/docs/examples/src/appkit/actions/staking/staking.test.ts similarity index 100% rename from demo/examples/src/appkit/actions/staking/staking.test.ts rename to docs/examples/src/appkit/actions/staking/staking.test.ts diff --git a/demo/examples/src/appkit/actions/swap/swap-actions.ts b/docs/examples/src/appkit/actions/swap/swap-actions.ts similarity index 100% rename from demo/examples/src/appkit/actions/swap/swap-actions.ts rename to docs/examples/src/appkit/actions/swap/swap-actions.ts diff --git a/demo/examples/src/appkit/actions/swap/swap.test.ts b/docs/examples/src/appkit/actions/swap/swap.test.ts similarity index 100% rename from demo/examples/src/appkit/actions/swap/swap.test.ts rename to docs/examples/src/appkit/actions/swap/swap.test.ts diff --git a/demo/examples/src/appkit/actions/transaction/create-transfer-ton-transaction.ts b/docs/examples/src/appkit/actions/transaction/create-transfer-ton-transaction.ts similarity index 91% rename from demo/examples/src/appkit/actions/transaction/create-transfer-ton-transaction.ts rename to docs/examples/src/appkit/actions/transaction/create-transfer-ton-transaction.ts index f2b47af87..1e18aa9d9 100644 --- a/demo/examples/src/appkit/actions/transaction/create-transfer-ton-transaction.ts +++ b/docs/examples/src/appkit/actions/transaction/create-transfer-ton-transaction.ts @@ -11,7 +11,7 @@ import { createTransferTonTransaction } from '@ton/appkit'; export const createTransferTonTransactionExample = async (appKit: AppKit) => { // SAMPLE_START: CREATE_TRANSFER_TON_TRANSACTION - const tx = await createTransferTonTransaction(appKit, { + const tx = createTransferTonTransaction(appKit, { recipientAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', amount: '0.1', // 0.1 TON (human-readable format) comment: 'Draft transaction', diff --git a/demo/examples/src/appkit/actions/transaction/send-transaction.ts b/docs/examples/src/appkit/actions/transaction/send-transaction.ts similarity index 100% rename from demo/examples/src/appkit/actions/transaction/send-transaction.ts rename to docs/examples/src/appkit/actions/transaction/send-transaction.ts diff --git a/demo/examples/src/appkit/actions/transaction/transaction.test.ts b/docs/examples/src/appkit/actions/transaction/transaction.test.ts similarity index 100% rename from demo/examples/src/appkit/actions/transaction/transaction.test.ts rename to docs/examples/src/appkit/actions/transaction/transaction.test.ts diff --git a/demo/examples/src/appkit/actions/transaction/transfer-ton.ts b/docs/examples/src/appkit/actions/transaction/transfer-ton.ts similarity index 100% rename from demo/examples/src/appkit/actions/transaction/transfer-ton.ts rename to docs/examples/src/appkit/actions/transaction/transfer-ton.ts diff --git a/demo/examples/src/appkit/actions/wallets/get-connected-wallets.ts b/docs/examples/src/appkit/actions/wallets/get-connected-wallets.ts similarity index 100% rename from demo/examples/src/appkit/actions/wallets/get-connected-wallets.ts rename to docs/examples/src/appkit/actions/wallets/get-connected-wallets.ts diff --git a/demo/examples/src/appkit/actions/wallets/get-selected-wallet.ts b/docs/examples/src/appkit/actions/wallets/get-selected-wallet.ts similarity index 100% rename from demo/examples/src/appkit/actions/wallets/get-selected-wallet.ts rename to docs/examples/src/appkit/actions/wallets/get-selected-wallet.ts diff --git a/demo/examples/src/appkit/actions/wallets/set-selected-wallet-id.ts b/docs/examples/src/appkit/actions/wallets/set-selected-wallet-id.ts similarity index 100% rename from demo/examples/src/appkit/actions/wallets/set-selected-wallet-id.ts rename to docs/examples/src/appkit/actions/wallets/set-selected-wallet-id.ts diff --git a/demo/examples/src/appkit/actions/wallets/wallets.test.ts b/docs/examples/src/appkit/actions/wallets/wallets.test.ts similarity index 100% rename from demo/examples/src/appkit/actions/wallets/wallets.test.ts rename to docs/examples/src/appkit/actions/wallets/wallets.test.ts diff --git a/demo/examples/src/appkit/actions/wallets/watch-connected-wallets.ts b/docs/examples/src/appkit/actions/wallets/watch-connected-wallets.ts similarity index 100% rename from demo/examples/src/appkit/actions/wallets/watch-connected-wallets.ts rename to docs/examples/src/appkit/actions/wallets/watch-connected-wallets.ts diff --git a/demo/examples/src/appkit/actions/wallets/watch-selected-wallet.ts b/docs/examples/src/appkit/actions/wallets/watch-selected-wallet.ts similarity index 100% rename from demo/examples/src/appkit/actions/wallets/watch-selected-wallet.ts rename to docs/examples/src/appkit/actions/wallets/watch-selected-wallet.ts diff --git a/demo/examples/src/appkit/components/balances/balances.test.tsx b/docs/examples/src/appkit/components/balances/balances.test.tsx similarity index 100% rename from demo/examples/src/appkit/components/balances/balances.test.tsx rename to docs/examples/src/appkit/components/balances/balances.test.tsx diff --git a/demo/examples/src/appkit/components/balances/send-jetton-button.tsx b/docs/examples/src/appkit/components/balances/send-jetton-button.tsx similarity index 100% rename from demo/examples/src/appkit/components/balances/send-jetton-button.tsx rename to docs/examples/src/appkit/components/balances/send-jetton-button.tsx diff --git a/demo/examples/src/appkit/components/balances/send-ton-button.tsx b/docs/examples/src/appkit/components/balances/send-ton-button.tsx similarity index 100% rename from demo/examples/src/appkit/components/balances/send-ton-button.tsx rename to docs/examples/src/appkit/components/balances/send-ton-button.tsx diff --git a/docs/examples/src/appkit/components/crypto-onramp/crypto-onramp-widget.tsx b/docs/examples/src/appkit/components/crypto-onramp/crypto-onramp-widget.tsx new file mode 100644 index 000000000..8c105f268 --- /dev/null +++ b/docs/examples/src/appkit/components/crypto-onramp/crypto-onramp-widget.tsx @@ -0,0 +1,17 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { CryptoOnrampWidget } from '@ton/appkit-react'; + +export const CryptoOnrampWidgetExample = () => { + // SAMPLE_START: CRYPTO_ONRAMP_WIDGET + // Uses built-in defaults for tokens, payment methods and chain display info. + // Make sure a crypto-onramp provider (Layerswap / swaps.xyz) is registered on AppKit. + return ; + // SAMPLE_END: CRYPTO_ONRAMP_WIDGET +}; diff --git a/docs/examples/src/appkit/components/crypto-onramp/crypto-onramp.test.tsx b/docs/examples/src/appkit/components/crypto-onramp/crypto-onramp.test.tsx new file mode 100644 index 000000000..7c408017a --- /dev/null +++ b/docs/examples/src/appkit/components/crypto-onramp/crypto-onramp.test.tsx @@ -0,0 +1,55 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +import { render, cleanup, screen } from '@testing-library/react'; +import { describe, it, expect, afterEach, beforeEach } from 'vitest'; +import { Network } from '@ton/walletkit'; + +import { createWrapper } from '../../../__tests__/test-utils'; +import { CryptoOnrampWidgetExample } from './crypto-onramp-widget'; + +describe('Crypto Onramp Component Examples', () => { + let mockAppKit: any; + + beforeEach(() => { + // Stable references — `useSyncExternalStore` re-renders on every snapshot + // identity change, so returning a fresh `[]` per call causes an infinite loop. + const networks = [Network.mainnet()]; + const providers: unknown[] = []; + mockAppKit = { + getDefaultNetwork: () => Network.mainnet(), + connectors: [], + walletsManager: { selectedWallet: null, getSelectedWallet: () => null }, + networkManager: { + getClient: () => ({}), + getDefaultNetwork: () => Network.mainnet(), + getConfiguredNetworks: () => networks, + getNetworks: () => networks, + }, + cryptoOnrampManager: { + getProviders: () => providers, + getProvider: () => undefined, + hasProvider: () => false, + }, + emitter: { on: () => () => {}, off: () => {} }, + }; + }); + + afterEach(() => cleanup()); + + // Confirms the SAMPLE comment: with no `tokens` / `paymentMethods` props, the + // widget surfaces its built-in TON target token (and renders without crashing). + it('CryptoOnrampWidgetExample falls back to built-in defaults when no tokens are supplied', () => { + render(, { wrapper: createWrapper(mockAppKit) }); + // `defaultTokenId="ton"` picks the built-in TON entry from `CRYPTO_ONRAMP_TARGET_TOKENS`. + // Multiple `TON` matches can appear (token ticker + chain name); at least one must. + expect(screen.getAllByText(/\bTON\b/).length).toBeGreaterThan(0); + }); +}); diff --git a/docs/examples/src/appkit/components/nfts/nft-item.tsx b/docs/examples/src/appkit/components/nfts/nft-item.tsx new file mode 100644 index 000000000..f2649cf87 --- /dev/null +++ b/docs/examples/src/appkit/components/nfts/nft-item.tsx @@ -0,0 +1,24 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable no-console */ + +import type { NFT } from '@ton/appkit'; +import { NftItem } from '@ton/appkit-react'; + +const sampleNft: NFT = { + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + info: { name: 'TON Diamond #42' }, + collection: { address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', name: 'TON Diamonds' }, +}; + +export const NftItemExample = () => { + // SAMPLE_START: NFT_ITEM + return console.log('NFT clicked')} />; + // SAMPLE_END: NFT_ITEM +}; diff --git a/docs/examples/src/appkit/components/nfts/nfts.test.tsx b/docs/examples/src/appkit/components/nfts/nfts.test.tsx new file mode 100644 index 000000000..4e19eb9ee --- /dev/null +++ b/docs/examples/src/appkit/components/nfts/nfts.test.tsx @@ -0,0 +1,37 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +import { render, screen, cleanup } from '@testing-library/react'; +import { describe, it, expect, afterEach, beforeEach } from 'vitest'; +import { Network } from '@ton/walletkit'; + +import { createWrapper } from '../../../__tests__/test-utils'; +import { NftItemExample } from './nft-item'; + +describe('NFTs Component Examples', () => { + let mockAppKit: any; + + beforeEach(() => { + mockAppKit = { + getDefaultNetwork: () => Network.mainnet(), + connectors: [], + walletsManager: { selectedWallet: null }, + networkManager: { getClient: () => ({}) }, + emitter: { on: () => () => {}, off: () => {} }, + }; + }); + + afterEach(() => cleanup()); + + it('NftItemExample renders the NFT name', () => { + render(, { wrapper: createWrapper(mockAppKit) }); + expect(screen.getByText('TON Diamond #42')).toBeDefined(); + }); +}); diff --git a/demo/examples/src/appkit/components/providers/app-kit-provider.tsx b/docs/examples/src/appkit/components/providers/app-kit-provider.tsx similarity index 97% rename from demo/examples/src/appkit/components/providers/app-kit-provider.tsx rename to docs/examples/src/appkit/components/providers/app-kit-provider.tsx index 3d8459f74..53d39b4c8 100644 --- a/demo/examples/src/appkit/components/providers/app-kit-provider.tsx +++ b/docs/examples/src/appkit/components/providers/app-kit-provider.tsx @@ -29,8 +29,8 @@ export const AppKitProviderExample: FC = () => { // SAMPLE_START: APP_KIT_PROVIDER return ( +

My App

{/* Your App Content */} -
My App
); // SAMPLE_END: APP_KIT_PROVIDER diff --git a/docs/examples/src/appkit/components/providers/i18n-provider.tsx b/docs/examples/src/appkit/components/providers/i18n-provider.tsx new file mode 100644 index 000000000..757f0092b --- /dev/null +++ b/docs/examples/src/appkit/components/providers/i18n-provider.tsx @@ -0,0 +1,21 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { I18nProvider } from '@ton/appkit-react'; +import type { FC } from 'react'; + +export const I18nProviderExample: FC = () => { + // SAMPLE_START: I18N_PROVIDER + // Override the locale. Pass `lngDicts` with your own translations when you need them. + return ( + +
My App
+
+ ); + // SAMPLE_END: I18N_PROVIDER +}; diff --git a/docs/examples/src/appkit/components/providers/providers.test.tsx b/docs/examples/src/appkit/components/providers/providers.test.tsx new file mode 100644 index 000000000..b091c0ad9 --- /dev/null +++ b/docs/examples/src/appkit/components/providers/providers.test.tsx @@ -0,0 +1,21 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { render, cleanup } from '@testing-library/react'; +import { describe, it, expect, afterEach } from 'vitest'; + +import { I18nProviderExample } from './i18n-provider'; + +describe('Providers Component Examples', () => { + afterEach(() => cleanup()); + + it('I18nProviderExample renders', () => { + const { container } = render(); + expect(container.textContent).toContain('My App'); + }); +}); diff --git a/docs/examples/src/appkit/components/shared/amount-presets.tsx b/docs/examples/src/appkit/components/shared/amount-presets.tsx new file mode 100644 index 000000000..087c2e1c6 --- /dev/null +++ b/docs/examples/src/appkit/components/shared/amount-presets.tsx @@ -0,0 +1,29 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { useState } from 'react'; +import { AmountPresets } from '@ton/appkit-react'; +import type { AmountPreset } from '@ton/appkit-react'; + +const presets: AmountPreset[] = [ + { label: '10', amount: '10' }, + { label: '50', amount: '50' }, + { label: '100', amount: '100' }, +]; + +export const AmountPresetsExample = () => { + const [amount, setAmount] = useState(''); + // SAMPLE_START: AMOUNT_PRESETS + return ( +
+ setAmount(e.target.value)} placeholder="Amount" /> + +
+ ); + // SAMPLE_END: AMOUNT_PRESETS +}; diff --git a/docs/examples/src/appkit/components/shared/copy-button.tsx b/docs/examples/src/appkit/components/shared/copy-button.tsx new file mode 100644 index 000000000..410394b64 --- /dev/null +++ b/docs/examples/src/appkit/components/shared/copy-button.tsx @@ -0,0 +1,15 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { CopyButton } from '@ton/appkit-react'; + +export const CopyButtonExample = () => { + // SAMPLE_START: COPY_BUTTON + return ; + // SAMPLE_END: COPY_BUTTON +}; diff --git a/docs/examples/src/appkit/components/shared/currency-item.tsx b/docs/examples/src/appkit/components/shared/currency-item.tsx new file mode 100644 index 000000000..256ab0082 --- /dev/null +++ b/docs/examples/src/appkit/components/shared/currency-item.tsx @@ -0,0 +1,28 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable no-console */ + +import { CurrencyItem } from '@ton/appkit-react'; + +export const CurrencyItemExample = () => { + // SAMPLE_START: CURRENCY_ITEM + // Top-level props give you the default layout in one line. + return ( + console.log('Picked USDT')} + /> + ); + // SAMPLE_END: CURRENCY_ITEM +}; diff --git a/docs/examples/src/appkit/components/shared/low-balance-modal.tsx b/docs/examples/src/appkit/components/shared/low-balance-modal.tsx new file mode 100644 index 000000000..e1bb6984f --- /dev/null +++ b/docs/examples/src/appkit/components/shared/low-balance-modal.tsx @@ -0,0 +1,30 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable no-console */ + +import { useState } from 'react'; +import { LowBalanceModal } from '@ton/appkit-react'; + +export const LowBalanceModalExample = () => { + const [open, setOpen] = useState(true); + // SAMPLE_START: LOW_BALANCE_MODAL + return ( + { + console.log('Reduce amount to fit balance'); + setOpen(false); + }} + onCancel={() => setOpen(false)} + /> + ); + // SAMPLE_END: LOW_BALANCE_MODAL +}; diff --git a/docs/examples/src/appkit/components/shared/option-switcher.tsx b/docs/examples/src/appkit/components/shared/option-switcher.tsx new file mode 100644 index 000000000..326c1d192 --- /dev/null +++ b/docs/examples/src/appkit/components/shared/option-switcher.tsx @@ -0,0 +1,24 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { useState } from 'react'; +import { OptionSwitcher } from '@ton/appkit-react'; +import type { OptionSwitcherOption } from '@ton/appkit-react'; + +const options: OptionSwitcherOption[] = [ + { value: 'all', label: 'All tokens' }, + { value: 'verified', label: 'Verified only' }, + { value: 'mine', label: 'My holdings' }, +]; + +export const OptionSwitcherExample = () => { + const [value, setValue] = useState('all'); + // SAMPLE_START: OPTION_SWITCHER + return ; + // SAMPLE_END: OPTION_SWITCHER +}; diff --git a/docs/examples/src/appkit/components/shared/settings-button.tsx b/docs/examples/src/appkit/components/shared/settings-button.tsx new file mode 100644 index 000000000..86f30342a --- /dev/null +++ b/docs/examples/src/appkit/components/shared/settings-button.tsx @@ -0,0 +1,17 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable no-console */ + +import { SettingsButton } from '@ton/appkit-react'; + +export const SettingsButtonExample = () => { + // SAMPLE_START: SETTINGS_BUTTON + return console.log('Open settings')} />; + // SAMPLE_END: SETTINGS_BUTTON +}; diff --git a/docs/examples/src/appkit/components/shared/shared.test.tsx b/docs/examples/src/appkit/components/shared/shared.test.tsx new file mode 100644 index 000000000..f983ada05 --- /dev/null +++ b/docs/examples/src/appkit/components/shared/shared.test.tsx @@ -0,0 +1,82 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +import { render, screen, cleanup } from '@testing-library/react'; +import { describe, it, expect, afterEach, beforeEach } from 'vitest'; +import { Network } from '@ton/walletkit'; + +import { createWrapper } from '../../../__tests__/test-utils'; +import { TokenSelectorExample } from './token-selector'; +import { TokenSelectModalExample } from './token-select-modal'; +import { LowBalanceModalExample } from './low-balance-modal'; +import { CopyButtonExample } from './copy-button'; +import { SettingsButtonExample } from './settings-button'; +import { AmountPresetsExample } from './amount-presets'; +import { OptionSwitcherExample } from './option-switcher'; +import { CurrencyItemExample } from './currency-item'; + +describe('Shared Component Examples', () => { + let mockAppKit: any; + + beforeEach(() => { + mockAppKit = { + getDefaultNetwork: () => Network.mainnet(), + connectors: [], + walletsManager: { selectedWallet: null }, + networkManager: { getClient: () => ({}) }, + emitter: { on: () => () => {}, off: () => {} }, + }; + }); + + afterEach(() => cleanup()); + + it('TokenSelectorExample renders', () => { + render(, { wrapper: createWrapper(mockAppKit) }); + expect(screen.getByRole('button')).toBeDefined(); + }); + + it('TokenSelectModalExample renders with a list of tokens', () => { + render(, { wrapper: createWrapper(mockAppKit) }); + expect(screen.getAllByText(/USDT|TON/).length).toBeGreaterThan(0); + }); + + it('LowBalanceModalExample renders the required TON amount', () => { + render(, { wrapper: createWrapper(mockAppKit) }); + expect(screen.getByText(/0\.423/)).toBeDefined(); + }); + + it('CopyButtonExample renders an accessible copy button', () => { + render(); + expect(screen.getByLabelText('Copy wallet address')).toBeDefined(); + }); + + it('SettingsButtonExample renders', () => { + render(, { wrapper: createWrapper(mockAppKit) }); + expect(screen.getByRole('button')).toBeDefined(); + }); + + it('AmountPresetsExample renders all preset buttons', () => { + render(); + const buttons = screen.getAllByRole('button'); + const labels = buttons.map((b) => b.textContent); + expect(labels).toEqual(expect.arrayContaining(['$10', '$50', '$100'])); + }); + + it('OptionSwitcherExample renders the active option label', () => { + render(); + expect(screen.getByText(/All tokens/)).toBeDefined(); + }); + + it('CurrencyItemExample renders the token name and ticker', () => { + render(); + expect(screen.getByText('Tether USD')).toBeDefined(); + expect(screen.getByText(/USDT/)).toBeDefined(); + }); +}); diff --git a/docs/examples/src/appkit/components/shared/token-select-modal.tsx b/docs/examples/src/appkit/components/shared/token-select-modal.tsx new file mode 100644 index 000000000..9613d4198 --- /dev/null +++ b/docs/examples/src/appkit/components/shared/token-select-modal.tsx @@ -0,0 +1,53 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable no-console */ + +import { useState } from 'react'; +import { Network } from '@ton/appkit'; +import { TokenSelectModal } from '@ton/appkit-react'; +import type { AppkitUIToken } from '@ton/appkit-react'; + +const tokens: AppkitUIToken[] = [ + { + id: 'ton', + symbol: 'TON', + name: 'Toncoin', + decimals: 9, + address: 'ton', + logo: 'https://ton.org/download/ton_symbol.png', + network: Network.mainnet(), + }, + { + id: 'usdt', + symbol: 'USDT', + name: 'Tether USD', + decimals: 6, + address: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs', + network: Network.mainnet(), + }, +]; + +export const TokenSelectModalExample = () => { + const [open, setOpen] = useState(true); + // SAMPLE_START: TOKEN_SELECT_MODAL + return ( + setOpen(false)} + tokens={tokens} + title="Select a token" + searchPlaceholder="Search by name or address" + onSelect={(token) => { + console.log('Picked:', token.symbol); + setOpen(false); + }} + /> + ); + // SAMPLE_END: TOKEN_SELECT_MODAL +}; diff --git a/docs/examples/src/appkit/components/shared/token-selector.tsx b/docs/examples/src/appkit/components/shared/token-selector.tsx new file mode 100644 index 000000000..c1c69e485 --- /dev/null +++ b/docs/examples/src/appkit/components/shared/token-selector.tsx @@ -0,0 +1,24 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable no-console */ + +import { TokenSelector } from '@ton/appkit-react'; + +export const TokenSelectorExample = () => { + // SAMPLE_START: TOKEN_SELECTOR + return ( + console.log('Open token picker')} + /> + ); + // SAMPLE_END: TOKEN_SELECTOR +}; diff --git a/docs/examples/src/appkit/components/staking/select-unstake-mode.tsx b/docs/examples/src/appkit/components/staking/select-unstake-mode.tsx new file mode 100644 index 000000000..1e7fcdd04 --- /dev/null +++ b/docs/examples/src/appkit/components/staking/select-unstake-mode.tsx @@ -0,0 +1,33 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { useState } from 'react'; +import { UnstakeMode } from '@ton/appkit'; +import type { StakingProviderMetadata, UnstakeModes } from '@ton/appkit'; +import { SelectUnstakeMode } from '@ton/appkit-react'; + +const tonstakersMetadata: StakingProviderMetadata = { + name: 'Tonstakers', + supportedUnstakeModes: [UnstakeMode.INSTANT, UnstakeMode.WHEN_AVAILABLE, UnstakeMode.ROUND_END], + supportsReversedQuote: true, + stakeToken: { ticker: 'TON', decimals: 9, address: 'ton' }, +}; + +export const SelectUnstakeModeExample = () => { + const [mode, setMode] = useState(UnstakeMode.INSTANT); + // SAMPLE_START: SELECT_UNSTAKE_MODE + return ( + + ); + // SAMPLE_END: SELECT_UNSTAKE_MODE +}; diff --git a/docs/examples/src/appkit/components/staking/staking-balance-block.tsx b/docs/examples/src/appkit/components/staking/staking-balance-block.tsx new file mode 100644 index 000000000..9172870c8 --- /dev/null +++ b/docs/examples/src/appkit/components/staking/staking-balance-block.tsx @@ -0,0 +1,34 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable no-console */ + +import { UnstakeMode } from '@ton/appkit'; +import type { StakingProviderMetadata } from '@ton/appkit'; +import { StakingBalanceBlock } from '@ton/appkit-react'; + +const tonstakersMetadata: StakingProviderMetadata = { + name: 'Tonstakers', + supportedUnstakeModes: [UnstakeMode.INSTANT, UnstakeMode.WHEN_AVAILABLE, UnstakeMode.ROUND_END], + supportsReversedQuote: true, + stakeToken: { ticker: 'TON', decimals: 9, address: 'ton' }, + receiveToken: { ticker: 'tsTON', decimals: 9, address: 'EQCkR1cGmnsE45N4TPDFhRdkA9oWFAFKzm0kQAcz2P0BJgY3' }, +}; + +export const StakingBalanceBlockExample = () => { + // SAMPLE_START: STAKING_BALANCE_BLOCK + return ( + console.log('Use max balance')} + /> + ); + // SAMPLE_END: STAKING_BALANCE_BLOCK +}; diff --git a/docs/examples/src/appkit/components/staking/staking-settings-modal.tsx b/docs/examples/src/appkit/components/staking/staking-settings-modal.tsx new file mode 100644 index 000000000..1cb757827 --- /dev/null +++ b/docs/examples/src/appkit/components/staking/staking-settings-modal.tsx @@ -0,0 +1,35 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable no-console */ + +import { useState } from 'react'; +import { Network } from '@ton/appkit'; +import type { StakingProvider } from '@ton/appkit'; +import { StakingSettingsModal } from '@ton/appkit-react'; + +export const StakingSettingsModalExample = () => { + const [open, setOpen] = useState(true); + // SAMPLE_START: STAKING_SETTINGS_MODAL + // Source `provider` and `providers` from `useStakingProvider` and + // `useStakingProviders` in real usage — they refresh as providers register + // through AppKit. + const provider: StakingProvider | undefined = undefined; + const providers: StakingProvider[] = []; + return ( + setOpen(false)} + provider={provider} + providers={providers} + onProviderChange={(id) => console.log('Switch to', id)} + network={Network.mainnet()} + /> + ); + // SAMPLE_END: STAKING_SETTINGS_MODAL +}; diff --git a/docs/examples/src/appkit/components/staking/staking-widget.tsx b/docs/examples/src/appkit/components/staking/staking-widget.tsx new file mode 100644 index 000000000..8d5460d6b --- /dev/null +++ b/docs/examples/src/appkit/components/staking/staking-widget.tsx @@ -0,0 +1,17 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { StakingWidget } from '@ton/appkit-react'; + +export const StakingWidgetExample = () => { + // SAMPLE_START: STAKING_WIDGET + // Falls back to the connected wallet's network when `network` is omitted. + // Make sure a staking provider (e.g. Tonstakers) is registered on AppKit. + return ; + // SAMPLE_END: STAKING_WIDGET +}; diff --git a/docs/examples/src/appkit/components/staking/staking.test.tsx b/docs/examples/src/appkit/components/staking/staking.test.tsx new file mode 100644 index 000000000..2de31c299 --- /dev/null +++ b/docs/examples/src/appkit/components/staking/staking.test.tsx @@ -0,0 +1,69 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +import { render, cleanup } from '@testing-library/react'; +import { describe, it, expect, afterEach, beforeEach } from 'vitest'; +import { Network } from '@ton/walletkit'; + +import { createWrapper } from '../../../__tests__/test-utils'; +import { StakingWidgetExample } from './staking-widget'; +import { SelectUnstakeModeExample } from './select-unstake-mode'; +import { StakingSettingsModalExample } from './staking-settings-modal'; +import { StakingBalanceBlockExample } from './staking-balance-block'; + +describe('Staking Component Examples', () => { + let mockAppKit: any; + + beforeEach(() => { + // Stable references — `useSyncExternalStore` re-renders on every snapshot + // identity change, so returning a fresh `[]` per call causes an infinite loop. + const networks = [Network.mainnet()]; + const providers: unknown[] = []; + mockAppKit = { + getDefaultNetwork: () => Network.mainnet(), + connectors: [], + walletsManager: { selectedWallet: null, getSelectedWallet: () => null }, + networkManager: { + getClient: () => ({}), + getDefaultNetwork: () => Network.mainnet(), + getConfiguredNetworks: () => networks, + getNetworks: () => networks, + }, + stakingManager: { + getProviders: () => providers, + getProvider: () => undefined, + hasProvider: () => false, + }, + emitter: { on: () => () => {}, off: () => {} }, + }; + }); + + afterEach(() => cleanup()); + + it('StakingWidgetExample renders without crashing', () => { + const { container } = render(, { wrapper: createWrapper(mockAppKit) }); + expect(container).toBeDefined(); + }); + + it('SelectUnstakeModeExample renders without crashing', () => { + const { container } = render(, { wrapper: createWrapper(mockAppKit) }); + expect(container).toBeDefined(); + }); + + it('StakingSettingsModalExample renders without crashing', () => { + const { container } = render(, { wrapper: createWrapper(mockAppKit) }); + expect(container).toBeDefined(); + }); + + it('StakingBalanceBlockExample renders without crashing', () => { + const { container } = render(, { wrapper: createWrapper(mockAppKit) }); + expect(container).toBeDefined(); + }); +}); diff --git a/docs/examples/src/appkit/components/swap/swap-field.tsx b/docs/examples/src/appkit/components/swap/swap-field.tsx new file mode 100644 index 000000000..62a76fa86 --- /dev/null +++ b/docs/examples/src/appkit/components/swap/swap-field.tsx @@ -0,0 +1,41 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable no-console */ + +import { useState } from 'react'; +import { Network } from '@ton/appkit'; +import { SwapField } from '@ton/appkit-react'; +import type { AppkitUIToken } from '@ton/appkit-react'; + +const ton: AppkitUIToken = { + id: 'ton', + symbol: 'TON', + name: 'Toncoin', + decimals: 9, + address: 'ton', + logo: 'https://ton.org/download/ton_symbol.png', + network: Network.mainnet(), +}; + +export const SwapFieldExample = () => { + const [amount, setAmount] = useState(''); + // SAMPLE_START: SWAP_FIELD + return ( + setAmount('12.5')} + onTokenSelectorClick={() => console.log('Open token picker')} + /> + ); + // SAMPLE_END: SWAP_FIELD +}; diff --git a/docs/examples/src/appkit/components/swap/swap-flip-button.tsx b/docs/examples/src/appkit/components/swap/swap-flip-button.tsx new file mode 100644 index 000000000..3fa3e79bd --- /dev/null +++ b/docs/examples/src/appkit/components/swap/swap-flip-button.tsx @@ -0,0 +1,18 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { useState } from 'react'; +import { SwapFlipButton } from '@ton/appkit-react'; + +export const SwapFlipButtonExample = () => { + const [rotated, setRotated] = useState(false); + // SAMPLE_START: SWAP_FLIP_BUTTON + // Drop it between the source and target `SwapField` rows. Wire `onClick` to your token-flip handler. + return setRotated((prev) => !prev)} />; + // SAMPLE_END: SWAP_FLIP_BUTTON +}; diff --git a/docs/examples/src/appkit/components/swap/swap-info.tsx b/docs/examples/src/appkit/components/swap/swap-info.tsx new file mode 100644 index 000000000..4705251ca --- /dev/null +++ b/docs/examples/src/appkit/components/swap/swap-info.tsx @@ -0,0 +1,29 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { Network } from '@ton/appkit'; +import { SwapInfo } from '@ton/appkit-react'; +import type { AppkitUIToken } from '@ton/appkit-react'; + +const toToken: AppkitUIToken = { + id: 'usdt', + symbol: 'USDT', + name: 'Tether USD', + decimals: 6, + address: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs', + network: Network.mainnet(), +}; + +export const SwapInfoExample = () => { + // SAMPLE_START: SWAP_INFO + // In the swap widget `quote` and `provider` come from `useSwapContext`; until + // those resolve the min-received row shows `0 USDT` and the provider row a + // skeleton placeholder. + return ; + // SAMPLE_END: SWAP_INFO +}; diff --git a/docs/examples/src/appkit/components/swap/swap-widget.tsx b/docs/examples/src/appkit/components/swap/swap-widget.tsx new file mode 100644 index 000000000..5b772b91d --- /dev/null +++ b/docs/examples/src/appkit/components/swap/swap-widget.tsx @@ -0,0 +1,38 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { Network } from '@ton/appkit'; +import { SwapWidget } from '@ton/appkit-react'; +import type { AppkitUIToken } from '@ton/appkit-react'; + +const tokens: AppkitUIToken[] = [ + { + id: 'ton', + symbol: 'TON', + name: 'Toncoin', + decimals: 9, + address: 'ton', + logo: 'https://ton.org/download/ton_symbol.png', + network: Network.mainnet(), + }, + { + id: 'usdt', + symbol: 'USDT', + name: 'Tether USD', + decimals: 6, + address: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs', + network: Network.mainnet(), + }, +]; + +export const SwapWidgetExample = () => { + // SAMPLE_START: SWAP_WIDGET + // Make sure a swap provider (e.g. DeDust / Omniston) is registered on AppKit. + return ; + // SAMPLE_END: SWAP_WIDGET +}; diff --git a/docs/examples/src/appkit/components/swap/swap.test.tsx b/docs/examples/src/appkit/components/swap/swap.test.tsx new file mode 100644 index 000000000..96d639cd6 --- /dev/null +++ b/docs/examples/src/appkit/components/swap/swap.test.tsx @@ -0,0 +1,75 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +import { render, cleanup, screen } from '@testing-library/react'; +import { describe, it, expect, afterEach, beforeEach } from 'vitest'; +import { Network } from '@ton/walletkit'; + +import { createWrapper } from '../../../__tests__/test-utils'; +import { SwapWidgetExample } from './swap-widget'; +import { SwapFieldExample } from './swap-field'; +import { SwapFlipButtonExample } from './swap-flip-button'; +import { SwapInfoExample } from './swap-info'; + +describe('Swap Component Examples', () => { + let mockAppKit: any; + + beforeEach(() => { + // Stable references — `useSyncExternalStore` re-renders on every snapshot + // identity change, so returning a fresh `[]` per call causes an infinite loop. + const networks = [Network.mainnet()]; + const providers: unknown[] = []; + mockAppKit = { + getDefaultNetwork: () => Network.mainnet(), + connectors: [], + walletsManager: { selectedWallet: null, getSelectedWallet: () => null }, + networkManager: { + getClient: () => ({}), + getDefaultNetwork: () => Network.mainnet(), + getConfiguredNetworks: () => networks, + getNetworks: () => networks, + }, + swapManager: { + getProviders: () => providers, + getProvider: () => undefined, + hasProvider: () => false, + }, + emitter: { on: () => () => {}, off: () => {} }, + }; + }); + + afterEach(() => cleanup()); + + it('SwapWidgetExample renders without crashing', () => { + const { container } = render(, { wrapper: createWrapper(mockAppKit) }); + expect(container).toBeDefined(); + }); + + it('SwapFieldExample renders the token ticker', () => { + render(, { wrapper: createWrapper(mockAppKit) }); + expect(screen.getByText('TON')).toBeDefined(); + }); + + it('SwapFlipButtonExample renders a clickable button', () => { + render(, { wrapper: createWrapper(mockAppKit) }); + expect(screen.getByRole('button')).toBeDefined(); + }); + + // Confirms the SAMPLE comment: with `quote` / `provider` undefined the + // min-received row reads `0 USDT` and the provider row falls back to a + // skeleton placeholder. + it('SwapInfoExample shows `0 USDT` for min-received and a skeleton for the provider when no quote is set', () => { + const { container } = render(, { wrapper: createWrapper(mockAppKit) }); + expect(screen.getByText(/0\s*USDT/)).toBeDefined(); + // Provider row falls back to ValueSkeleton — assert a skeleton element exists. + const skeleton = container.querySelector('[class*="skeleton" i]'); + expect(skeleton).not.toBeNull(); + }); +}); diff --git a/demo/examples/src/appkit/components/transaction/transaction.test.tsx b/docs/examples/src/appkit/components/transaction/transaction.test.tsx similarity index 100% rename from demo/examples/src/appkit/components/transaction/transaction.test.tsx rename to docs/examples/src/appkit/components/transaction/transaction.test.tsx diff --git a/demo/examples/src/appkit/components/transaction/transaction.tsx b/docs/examples/src/appkit/components/transaction/transaction.tsx similarity index 100% rename from demo/examples/src/appkit/components/transaction/transaction.tsx rename to docs/examples/src/appkit/components/transaction/transaction.tsx diff --git a/docs/examples/src/appkit/components/ui/block.tsx b/docs/examples/src/appkit/components/ui/block.tsx new file mode 100644 index 000000000..1167e1f8d --- /dev/null +++ b/docs/examples/src/appkit/components/ui/block.tsx @@ -0,0 +1,20 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { Block } from '@ton/appkit-react'; + +export const BlockExample = () => { + // SAMPLE_START: BLOCK + return ( + + Left + Right + + ); + // SAMPLE_END: BLOCK +}; diff --git a/docs/examples/src/appkit/components/ui/button.tsx b/docs/examples/src/appkit/components/ui/button.tsx new file mode 100644 index 000000000..68a8d4bae --- /dev/null +++ b/docs/examples/src/appkit/components/ui/button.tsx @@ -0,0 +1,21 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/* eslint-disable no-console */ + +import { Button } from '@ton/appkit-react'; + +export const ButtonExample = () => { + // SAMPLE_START: BUTTON + return ( + + ); + // SAMPLE_END: BUTTON +}; diff --git a/docs/examples/src/appkit/components/ui/centered-amount-input.tsx b/docs/examples/src/appkit/components/ui/centered-amount-input.tsx new file mode 100644 index 000000000..44584907a --- /dev/null +++ b/docs/examples/src/appkit/components/ui/centered-amount-input.tsx @@ -0,0 +1,17 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { useState } from 'react'; +import { CenteredAmountInput } from '@ton/appkit-react'; + +export const CenteredAmountInputExample = () => { + const [amount, setAmount] = useState(''); + // SAMPLE_START: CENTERED_AMOUNT_INPUT + return ; + // SAMPLE_END: CENTERED_AMOUNT_INPUT +}; diff --git a/docs/examples/src/appkit/components/ui/collapsible.tsx b/docs/examples/src/appkit/components/ui/collapsible.tsx new file mode 100644 index 000000000..51bcd88c5 --- /dev/null +++ b/docs/examples/src/appkit/components/ui/collapsible.tsx @@ -0,0 +1,24 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { useState } from 'react'; +import { Collapsible } from '@ton/appkit-react'; + +export const CollapsibleExample = () => { + const [open, setOpen] = useState(false); + // SAMPLE_START: COLLAPSIBLE + return ( +
+ + +

Hidden details about the transaction.

+
+
+ ); + // SAMPLE_END: COLLAPSIBLE +}; diff --git a/docs/examples/src/appkit/components/ui/info-block.tsx b/docs/examples/src/appkit/components/ui/info-block.tsx new file mode 100644 index 000000000..7f18446d6 --- /dev/null +++ b/docs/examples/src/appkit/components/ui/info-block.tsx @@ -0,0 +1,26 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { InfoBlock } from '@ton/appkit-react'; + +export const InfoBlockExample = () => { + // SAMPLE_START: INFO_BLOCK + return ( + + + Rate + 1 TON ≈ $5.43 + + + Network fee + 0.01 TON + + + ); + // SAMPLE_END: INFO_BLOCK +}; diff --git a/docs/examples/src/appkit/components/ui/input.tsx b/docs/examples/src/appkit/components/ui/input.tsx new file mode 100644 index 000000000..b609da51d --- /dev/null +++ b/docs/examples/src/appkit/components/ui/input.tsx @@ -0,0 +1,27 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { useState } from 'react'; +import { Input } from '@ton/appkit-react'; + +export const InputExample = () => { + const [value, setValue] = useState(''); + // SAMPLE_START: INPUT + return ( + + + Recipient + + + setValue(event.target.value)} placeholder="EQ..." /> + + Paste a TON wallet address. + + ); + // SAMPLE_END: INPUT +}; diff --git a/docs/examples/src/appkit/components/ui/logo-with-network.tsx b/docs/examples/src/appkit/components/ui/logo-with-network.tsx new file mode 100644 index 000000000..ebdc01d51 --- /dev/null +++ b/docs/examples/src/appkit/components/ui/logo-with-network.tsx @@ -0,0 +1,24 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { LogoWithNetwork } from '@ton/appkit-react'; + +export const LogoWithNetworkExample = () => { + // SAMPLE_START: LOGO_WITH_NETWORK + return ( + + ); + // SAMPLE_END: LOGO_WITH_NETWORK +}; diff --git a/docs/examples/src/appkit/components/ui/logo.tsx b/docs/examples/src/appkit/components/ui/logo.tsx new file mode 100644 index 000000000..69f332970 --- /dev/null +++ b/docs/examples/src/appkit/components/ui/logo.tsx @@ -0,0 +1,15 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { Logo } from '@ton/appkit-react'; + +export const LogoExample = () => { + // SAMPLE_START: LOGO + return ; + // SAMPLE_END: LOGO +}; diff --git a/docs/examples/src/appkit/components/ui/modal.tsx b/docs/examples/src/appkit/components/ui/modal.tsx new file mode 100644 index 000000000..249965c68 --- /dev/null +++ b/docs/examples/src/appkit/components/ui/modal.tsx @@ -0,0 +1,24 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { useState } from 'react'; +import { Modal } from '@ton/appkit-react'; + +export const ModalExample = () => { + const [open, setOpen] = useState(false); + // SAMPLE_START: MODAL + return ( +
+ + +

Are you sure you want to proceed?

+
+
+ ); + // SAMPLE_END: MODAL +}; diff --git a/docs/examples/src/appkit/components/ui/select.tsx b/docs/examples/src/appkit/components/ui/select.tsx new file mode 100644 index 000000000..939d1c76a --- /dev/null +++ b/docs/examples/src/appkit/components/ui/select.tsx @@ -0,0 +1,25 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { useState } from 'react'; +import { Select } from '@ton/appkit-react'; + +export const SelectExample = () => { + const [value, setValue] = useState('mainnet'); + // SAMPLE_START: SELECT + return ( + + {value === 'mainnet' ? 'Mainnet' : 'Testnet'} + + Mainnet + Testnet + + + ); + // SAMPLE_END: SELECT +}; diff --git a/docs/examples/src/appkit/components/ui/skeleton.tsx b/docs/examples/src/appkit/components/ui/skeleton.tsx new file mode 100644 index 000000000..b8698d204 --- /dev/null +++ b/docs/examples/src/appkit/components/ui/skeleton.tsx @@ -0,0 +1,15 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { Skeleton } from '@ton/appkit-react'; + +export const SkeletonExample = () => { + // SAMPLE_START: SKELETON + return ; + // SAMPLE_END: SKELETON +}; diff --git a/docs/examples/src/appkit/components/ui/tabs.tsx b/docs/examples/src/appkit/components/ui/tabs.tsx new file mode 100644 index 000000000..63bd27c0b --- /dev/null +++ b/docs/examples/src/appkit/components/ui/tabs.tsx @@ -0,0 +1,30 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { useState } from 'react'; +import { Tabs, TabsList, TabsTrigger, TabsContent } from '@ton/appkit-react'; + +export const TabsExample = () => { + const [tab, setTab] = useState('stake'); + // SAMPLE_START: TABS + return ( + + + Stake + Unstake + + +

Stake your TON to earn rewards.

+
+ +

Withdraw your staked TON.

+
+
+ ); + // SAMPLE_END: TABS +}; diff --git a/docs/examples/src/appkit/components/ui/ui.test.tsx b/docs/examples/src/appkit/components/ui/ui.test.tsx new file mode 100644 index 000000000..fe055f91c --- /dev/null +++ b/docs/examples/src/appkit/components/ui/ui.test.tsx @@ -0,0 +1,104 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { render, screen, cleanup, act } from '@testing-library/react'; +import { describe, it, expect, afterEach } from 'vitest'; + +import { LogoExample } from './logo'; +import { LogoWithNetworkExample } from './logo-with-network'; +import { ModalExample } from './modal'; +import { BlockExample } from './block'; +import { ButtonExample } from './button'; +import { CenteredAmountInputExample } from './centered-amount-input'; +import { CollapsibleExample } from './collapsible'; +import { SkeletonExample } from './skeleton'; +import { TabsExample } from './tabs'; +import { InputExample } from './input'; +import { SelectExample } from './select'; +import { InfoBlockExample } from './info-block'; + +describe('UI Component Examples', () => { + afterEach(() => cleanup()); + + it('LogoExample renders the logo wrapper', () => { + const { container } = render(); + // Logo shows a placeholder until the image loads in the browser; in JSDOM the + // placeholder span is what we can assert on. + expect(container.firstElementChild).not.toBeNull(); + }); + + it('LogoWithNetworkExample renders both the main logo and the network badge wrappers', () => { + const { container } = render(); + // Two nested logo wrappers: the main one and the badge overlay. + const logos = container.querySelectorAll('span > span'); + expect(logos.length).toBeGreaterThanOrEqual(2); + }); + + it('ModalExample exposes a trigger that opens the modal', () => { + render(); + const trigger = screen.getByRole('button', { name: /open modal/i }); + expect(trigger).toBeDefined(); + act(() => trigger.click()); + expect(screen.getByText(/Are you sure/)).toBeDefined(); + }); + + it('BlockExample renders both children', () => { + render(); + expect(screen.getByText('Left')).toBeDefined(); + expect(screen.getByText('Right')).toBeDefined(); + }); + + it('ButtonExample renders a clickable button', () => { + render(); + expect(screen.getByRole('button', { name: /Send transaction/ })).toBeDefined(); + }); + + it('CenteredAmountInputExample renders an input with the ticker', () => { + render(); + // The component duplicates the ticker in a hidden measurement span, so + // there can be more than one match. + expect(screen.getAllByText('TON').length).toBeGreaterThanOrEqual(1); + }); + + it('CollapsibleExample toggles details on click', () => { + render(); + const trigger = screen.getByRole('button', { name: /Show details/ }); + expect(trigger).toBeDefined(); + act(() => trigger.click()); + expect(screen.getByRole('button', { name: /Hide details/ })).toBeDefined(); + }); + + it('SkeletonExample renders a placeholder element', () => { + const { container } = render(); + expect(container.firstElementChild).not.toBeNull(); + }); + + it('TabsExample renders both triggers and the active panel', () => { + render(); + expect(screen.getByRole('tab', { name: /Stake/ })).toBeDefined(); + expect(screen.getByRole('tab', { name: /Unstake/ })).toBeDefined(); + expect(screen.getByText(/Stake your TON/)).toBeDefined(); + }); + + it('InputExample renders the title and field', () => { + render(); + expect(screen.getByText('Recipient')).toBeDefined(); + expect(screen.getByPlaceholderText(/EQ\.\.\./)).toBeDefined(); + }); + + it('SelectExample renders the current label inside the trigger', () => { + render(); + expect(screen.getByText('Mainnet')).toBeDefined(); + }); + + it('InfoBlockExample renders label/value rows', () => { + render(); + expect(screen.getByText('Rate')).toBeDefined(); + expect(screen.getByText('1 TON ≈ $5.43')).toBeDefined(); + }); +}); diff --git a/demo/examples/src/appkit/components/wallets/connect-button.tsx b/docs/examples/src/appkit/components/wallets/connect-button.tsx similarity index 100% rename from demo/examples/src/appkit/components/wallets/connect-button.tsx rename to docs/examples/src/appkit/components/wallets/connect-button.tsx diff --git a/demo/examples/src/appkit/connectors/tonconnect/connector.ts b/docs/examples/src/appkit/connectors/tonconnect/connector.ts similarity index 100% rename from demo/examples/src/appkit/connectors/tonconnect/connector.ts rename to docs/examples/src/appkit/connectors/tonconnect/connector.ts diff --git a/demo/examples/src/appkit/hooks/balances/balances.test.tsx b/docs/examples/src/appkit/hooks/balances/balances.test.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/balances/balances.test.tsx rename to docs/examples/src/appkit/hooks/balances/balances.test.tsx diff --git a/demo/examples/src/appkit/hooks/balances/use-balance-by-address.tsx b/docs/examples/src/appkit/hooks/balances/use-balance-by-address.tsx similarity index 92% rename from demo/examples/src/appkit/hooks/balances/use-balance-by-address.tsx rename to docs/examples/src/appkit/hooks/balances/use-balance-by-address.tsx index 1eafbf243..4847cec37 100644 --- a/demo/examples/src/appkit/hooks/balances/use-balance-by-address.tsx +++ b/docs/examples/src/appkit/hooks/balances/use-balance-by-address.tsx @@ -26,6 +26,6 @@ export const UseBalanceByAddressExample = () => { return
Error: {error.message}
; } - return
Balance: {balance?.toString()}
; + return
Balance: {balance}
; // SAMPLE_END: USE_BALANCE_BY_ADDRESS }; diff --git a/demo/examples/src/appkit/hooks/balances/use-balance.tsx b/docs/examples/src/appkit/hooks/balances/use-balance.tsx similarity index 90% rename from demo/examples/src/appkit/hooks/balances/use-balance.tsx rename to docs/examples/src/appkit/hooks/balances/use-balance.tsx index d924eda3d..213b7d90e 100644 --- a/demo/examples/src/appkit/hooks/balances/use-balance.tsx +++ b/docs/examples/src/appkit/hooks/balances/use-balance.tsx @@ -20,6 +20,6 @@ export const UseBalanceExample = () => { return
Error: {error.message}
; } - return
Balance: {balance?.toString()}
; + return
Balance: {balance}
; // SAMPLE_END: USE_BALANCE }; diff --git a/demo/examples/src/appkit/hooks/balances/use-watch-balance-by-address.tsx b/docs/examples/src/appkit/hooks/balances/use-watch-balance-by-address.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/balances/use-watch-balance-by-address.tsx rename to docs/examples/src/appkit/hooks/balances/use-watch-balance-by-address.tsx diff --git a/demo/examples/src/appkit/hooks/balances/use-watch-balance.tsx b/docs/examples/src/appkit/hooks/balances/use-watch-balance.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/balances/use-watch-balance.tsx rename to docs/examples/src/appkit/hooks/balances/use-watch-balance.tsx diff --git a/demo/examples/src/appkit/hooks/core/use-app-kit-theme.tsx b/docs/examples/src/appkit/hooks/core/use-app-kit-theme.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/core/use-app-kit-theme.tsx rename to docs/examples/src/appkit/hooks/core/use-app-kit-theme.tsx diff --git a/demo/examples/src/appkit/hooks/core/use-app-kit.tsx b/docs/examples/src/appkit/hooks/core/use-app-kit.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/core/use-app-kit.tsx rename to docs/examples/src/appkit/hooks/core/use-app-kit.tsx diff --git a/demo/examples/src/appkit/hooks/jettons/jettons.test.tsx b/docs/examples/src/appkit/hooks/jettons/jettons.test.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/jettons/jettons.test.tsx rename to docs/examples/src/appkit/hooks/jettons/jettons.test.tsx diff --git a/demo/examples/src/appkit/hooks/jettons/use-jetton-balance-by-address.tsx b/docs/examples/src/appkit/hooks/jettons/use-jetton-balance-by-address.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/jettons/use-jetton-balance-by-address.tsx rename to docs/examples/src/appkit/hooks/jettons/use-jetton-balance-by-address.tsx diff --git a/demo/examples/src/appkit/hooks/jettons/use-jetton-info.tsx b/docs/examples/src/appkit/hooks/jettons/use-jetton-info.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/jettons/use-jetton-info.tsx rename to docs/examples/src/appkit/hooks/jettons/use-jetton-info.tsx diff --git a/demo/examples/src/appkit/hooks/jettons/use-jetton-wallet-address.tsx b/docs/examples/src/appkit/hooks/jettons/use-jetton-wallet-address.tsx similarity index 76% rename from demo/examples/src/appkit/hooks/jettons/use-jetton-wallet-address.tsx rename to docs/examples/src/appkit/hooks/jettons/use-jetton-wallet-address.tsx index 06f1fbde4..fe6da79ef 100644 --- a/demo/examples/src/appkit/hooks/jettons/use-jetton-wallet-address.tsx +++ b/docs/examples/src/appkit/hooks/jettons/use-jetton-wallet-address.tsx @@ -6,14 +6,6 @@ * */ -/** - * Copyright (c) TonTech. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - */ - import { useJettonWalletAddress } from '@ton/appkit-react'; export const UseJettonWalletAddressExample = () => { @@ -35,6 +27,6 @@ export const UseJettonWalletAddressExample = () => { return
Error: {error.message}
; } - return
Jetton Wallet Address: {walletAddress?.toString()}
; + return
Jetton Wallet Address: {walletAddress}
; // SAMPLE_END: USE_JETTON_WALLET_ADDRESS }; diff --git a/demo/examples/src/appkit/hooks/jettons/use-jettons-by-address.tsx b/docs/examples/src/appkit/hooks/jettons/use-jettons-by-address.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/jettons/use-jettons-by-address.tsx rename to docs/examples/src/appkit/hooks/jettons/use-jettons-by-address.tsx diff --git a/demo/examples/src/appkit/hooks/jettons/use-jettons.tsx b/docs/examples/src/appkit/hooks/jettons/use-jettons.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/jettons/use-jettons.tsx rename to docs/examples/src/appkit/hooks/jettons/use-jettons.tsx diff --git a/demo/examples/src/appkit/hooks/jettons/use-transfer-jetton.tsx b/docs/examples/src/appkit/hooks/jettons/use-transfer-jetton.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/jettons/use-transfer-jetton.tsx rename to docs/examples/src/appkit/hooks/jettons/use-transfer-jetton.tsx diff --git a/demo/examples/src/appkit/hooks/jettons/use-watch-jettons-by-address.tsx b/docs/examples/src/appkit/hooks/jettons/use-watch-jettons-by-address.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/jettons/use-watch-jettons-by-address.tsx rename to docs/examples/src/appkit/hooks/jettons/use-watch-jettons-by-address.tsx diff --git a/demo/examples/src/appkit/hooks/jettons/use-watch-jettons.tsx b/docs/examples/src/appkit/hooks/jettons/use-watch-jettons.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/jettons/use-watch-jettons.tsx rename to docs/examples/src/appkit/hooks/jettons/use-watch-jettons.tsx diff --git a/demo/examples/src/appkit/hooks/network/networks.test.tsx b/docs/examples/src/appkit/hooks/network/networks.test.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/network/networks.test.tsx rename to docs/examples/src/appkit/hooks/network/networks.test.tsx diff --git a/demo/examples/src/appkit/hooks/network/use-block-number.tsx b/docs/examples/src/appkit/hooks/network/use-block-number.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/network/use-block-number.tsx rename to docs/examples/src/appkit/hooks/network/use-block-number.tsx diff --git a/demo/examples/src/appkit/hooks/network/use-default-network.tsx b/docs/examples/src/appkit/hooks/network/use-default-network.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/network/use-default-network.tsx rename to docs/examples/src/appkit/hooks/network/use-default-network.tsx diff --git a/demo/examples/src/appkit/hooks/network/use-network.tsx b/docs/examples/src/appkit/hooks/network/use-network.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/network/use-network.tsx rename to docs/examples/src/appkit/hooks/network/use-network.tsx diff --git a/demo/examples/src/appkit/hooks/network/use-networks.tsx b/docs/examples/src/appkit/hooks/network/use-networks.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/network/use-networks.tsx rename to docs/examples/src/appkit/hooks/network/use-networks.tsx diff --git a/demo/examples/src/appkit/hooks/nft/nfts.test.tsx b/docs/examples/src/appkit/hooks/nft/nfts.test.tsx similarity index 93% rename from demo/examples/src/appkit/hooks/nft/nfts.test.tsx rename to docs/examples/src/appkit/hooks/nft/nfts.test.tsx index 249f640b9..78e2d935f 100644 --- a/demo/examples/src/appkit/hooks/nft/nfts.test.tsx +++ b/docs/examples/src/appkit/hooks/nft/nfts.test.tsx @@ -12,7 +12,6 @@ import React from 'react'; import { describe, it, expect, vi, beforeEach } from 'vitest'; import { render, screen, fireEvent } from '@testing-library/react'; import * as AppKitReact from '@ton/appkit-react'; -import { Address } from '@ton/core'; import { UseNftExample } from './use-nft'; import { UseNftsByAddressExample } from './use-nfts-by-address'; @@ -67,7 +66,7 @@ describe('NFT Hooks Examples', () => { data: { info: { name: 'Epic NFT' }, collection: { name: 'Epic Collection' }, - ownerAddress: Address.parse('EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c'), + ownerAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', }, error: null, // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -87,7 +86,7 @@ describe('NFT Hooks Examples', () => { data: { nfts: [ { - address: Address.parse('EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c'), + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', info: { name: 'NFT 1' }, collection: { name: 'Coll 1' }, }, @@ -110,7 +109,7 @@ describe('NFT Hooks Examples', () => { data: { nfts: [ { - address: Address.parse('EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c'), + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', info: { name: 'My NFT' }, collection: { name: 'My Coll' }, }, diff --git a/demo/examples/src/appkit/hooks/nft/use-nft.tsx b/docs/examples/src/appkit/hooks/nft/use-nft.tsx similarity index 93% rename from demo/examples/src/appkit/hooks/nft/use-nft.tsx rename to docs/examples/src/appkit/hooks/nft/use-nft.tsx index 54b87f1de..2f9986290 100644 --- a/demo/examples/src/appkit/hooks/nft/use-nft.tsx +++ b/docs/examples/src/appkit/hooks/nft/use-nft.tsx @@ -31,7 +31,7 @@ export const UseNftExample = () => {

NFT Details

Name: {nft?.info?.name}

Collection: {nft?.collection?.name}

-

Owner: {nft?.ownerAddress?.toString()}

+

Owner: {nft?.ownerAddress}

); // SAMPLE_END: USE_NFT diff --git a/demo/examples/src/appkit/hooks/nft/use-nfts-by-address.tsx b/docs/examples/src/appkit/hooks/nft/use-nfts-by-address.tsx similarity index 94% rename from demo/examples/src/appkit/hooks/nft/use-nfts-by-address.tsx rename to docs/examples/src/appkit/hooks/nft/use-nfts-by-address.tsx index be0901907..a4d9f3c3c 100644 --- a/demo/examples/src/appkit/hooks/nft/use-nfts-by-address.tsx +++ b/docs/examples/src/appkit/hooks/nft/use-nfts-by-address.tsx @@ -32,7 +32,7 @@ export const UseNftsByAddressExample = () => {

NFTs

    {nfts?.nfts.map((nft) => ( -
  • +
  • {nft.info?.name} ({nft.collection?.name})
  • ))} diff --git a/demo/examples/src/appkit/hooks/nft/use-nfts.tsx b/docs/examples/src/appkit/hooks/nft/use-nfts.tsx similarity index 93% rename from demo/examples/src/appkit/hooks/nft/use-nfts.tsx rename to docs/examples/src/appkit/hooks/nft/use-nfts.tsx index 8a710f252..d6005c172 100644 --- a/demo/examples/src/appkit/hooks/nft/use-nfts.tsx +++ b/docs/examples/src/appkit/hooks/nft/use-nfts.tsx @@ -31,7 +31,7 @@ export const UseNftsExample = () => {

    My NFTs

      {nfts?.nfts.map((nft) => ( -
    • +
    • {nft.info?.name} ({nft.collection?.name})
    • ))} diff --git a/demo/examples/src/appkit/hooks/nft/use-transfer-nft.tsx b/docs/examples/src/appkit/hooks/nft/use-transfer-nft.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/nft/use-transfer-nft.tsx rename to docs/examples/src/appkit/hooks/nft/use-transfer-nft.tsx diff --git a/demo/examples/src/appkit/hooks/onramp/use-crypto-onramp-provider.tsx b/docs/examples/src/appkit/hooks/onramp/use-crypto-onramp-provider.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/onramp/use-crypto-onramp-provider.tsx rename to docs/examples/src/appkit/hooks/onramp/use-crypto-onramp-provider.tsx diff --git a/demo/examples/src/appkit/hooks/onramp/use-crypto-onramp-providers.tsx b/docs/examples/src/appkit/hooks/onramp/use-crypto-onramp-providers.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/onramp/use-crypto-onramp-providers.tsx rename to docs/examples/src/appkit/hooks/onramp/use-crypto-onramp-providers.tsx diff --git a/demo/examples/src/appkit/hooks/signing/signing.test.tsx b/docs/examples/src/appkit/hooks/signing/signing.test.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/signing/signing.test.tsx rename to docs/examples/src/appkit/hooks/signing/signing.test.tsx diff --git a/demo/examples/src/appkit/hooks/signing/use-sign-binary.tsx b/docs/examples/src/appkit/hooks/signing/use-sign-binary.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/signing/use-sign-binary.tsx rename to docs/examples/src/appkit/hooks/signing/use-sign-binary.tsx diff --git a/demo/examples/src/appkit/hooks/signing/use-sign-cell.tsx b/docs/examples/src/appkit/hooks/signing/use-sign-cell.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/signing/use-sign-cell.tsx rename to docs/examples/src/appkit/hooks/signing/use-sign-cell.tsx diff --git a/demo/examples/src/appkit/hooks/signing/use-sign-text.tsx b/docs/examples/src/appkit/hooks/signing/use-sign-text.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/signing/use-sign-text.tsx rename to docs/examples/src/appkit/hooks/signing/use-sign-text.tsx diff --git a/demo/examples/src/appkit/hooks/staking/staking.test.tsx b/docs/examples/src/appkit/hooks/staking/staking.test.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/staking/staking.test.tsx rename to docs/examples/src/appkit/hooks/staking/staking.test.tsx diff --git a/demo/examples/src/appkit/hooks/staking/use-build-stake-transaction.tsx b/docs/examples/src/appkit/hooks/staking/use-build-stake-transaction.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/staking/use-build-stake-transaction.tsx rename to docs/examples/src/appkit/hooks/staking/use-build-stake-transaction.tsx diff --git a/demo/examples/src/appkit/hooks/staking/use-staked-balance.tsx b/docs/examples/src/appkit/hooks/staking/use-staked-balance.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/staking/use-staked-balance.tsx rename to docs/examples/src/appkit/hooks/staking/use-staked-balance.tsx diff --git a/demo/examples/src/appkit/hooks/staking/use-staking-provider-info.tsx b/docs/examples/src/appkit/hooks/staking/use-staking-provider-info.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/staking/use-staking-provider-info.tsx rename to docs/examples/src/appkit/hooks/staking/use-staking-provider-info.tsx diff --git a/demo/examples/src/appkit/hooks/staking/use-staking-provider-metadata.tsx b/docs/examples/src/appkit/hooks/staking/use-staking-provider-metadata.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/staking/use-staking-provider-metadata.tsx rename to docs/examples/src/appkit/hooks/staking/use-staking-provider-metadata.tsx diff --git a/demo/examples/src/appkit/hooks/staking/use-staking-provider.tsx b/docs/examples/src/appkit/hooks/staking/use-staking-provider.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/staking/use-staking-provider.tsx rename to docs/examples/src/appkit/hooks/staking/use-staking-provider.tsx diff --git a/demo/examples/src/appkit/hooks/staking/use-staking-providers.tsx b/docs/examples/src/appkit/hooks/staking/use-staking-providers.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/staking/use-staking-providers.tsx rename to docs/examples/src/appkit/hooks/staking/use-staking-providers.tsx diff --git a/demo/examples/src/appkit/hooks/staking/use-staking-quote.tsx b/docs/examples/src/appkit/hooks/staking/use-staking-quote.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/staking/use-staking-quote.tsx rename to docs/examples/src/appkit/hooks/staking/use-staking-quote.tsx diff --git a/demo/examples/src/appkit/hooks/swap/swap.test.tsx b/docs/examples/src/appkit/hooks/swap/swap.test.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/swap/swap.test.tsx rename to docs/examples/src/appkit/hooks/swap/swap.test.tsx diff --git a/demo/examples/src/appkit/hooks/swap/use-build-swap-transaction.tsx b/docs/examples/src/appkit/hooks/swap/use-build-swap-transaction.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/swap/use-build-swap-transaction.tsx rename to docs/examples/src/appkit/hooks/swap/use-build-swap-transaction.tsx diff --git a/demo/examples/src/appkit/hooks/swap/use-swap-provider.tsx b/docs/examples/src/appkit/hooks/swap/use-swap-provider.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/swap/use-swap-provider.tsx rename to docs/examples/src/appkit/hooks/swap/use-swap-provider.tsx diff --git a/demo/examples/src/appkit/hooks/swap/use-swap-providers.tsx b/docs/examples/src/appkit/hooks/swap/use-swap-providers.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/swap/use-swap-providers.tsx rename to docs/examples/src/appkit/hooks/swap/use-swap-providers.tsx diff --git a/demo/examples/src/appkit/hooks/swap/use-swap-quote.tsx b/docs/examples/src/appkit/hooks/swap/use-swap-quote.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/swap/use-swap-quote.tsx rename to docs/examples/src/appkit/hooks/swap/use-swap-quote.tsx diff --git a/demo/examples/src/appkit/hooks/transaction/transaction.test.tsx b/docs/examples/src/appkit/hooks/transaction/transaction.test.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/transaction/transaction.test.tsx rename to docs/examples/src/appkit/hooks/transaction/transaction.test.tsx diff --git a/demo/examples/src/appkit/hooks/transaction/use-send-transaction.tsx b/docs/examples/src/appkit/hooks/transaction/use-send-transaction.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/transaction/use-send-transaction.tsx rename to docs/examples/src/appkit/hooks/transaction/use-send-transaction.tsx diff --git a/demo/examples/src/appkit/hooks/transaction/use-transfer-ton.tsx b/docs/examples/src/appkit/hooks/transaction/use-transfer-ton.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/transaction/use-transfer-ton.tsx rename to docs/examples/src/appkit/hooks/transaction/use-transfer-ton.tsx diff --git a/demo/examples/src/appkit/hooks/transaction/use-watch-transactions-by-address.tsx b/docs/examples/src/appkit/hooks/transaction/use-watch-transactions-by-address.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/transaction/use-watch-transactions-by-address.tsx rename to docs/examples/src/appkit/hooks/transaction/use-watch-transactions-by-address.tsx diff --git a/demo/examples/src/appkit/hooks/transaction/use-watch-transactions.tsx b/docs/examples/src/appkit/hooks/transaction/use-watch-transactions.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/transaction/use-watch-transactions.tsx rename to docs/examples/src/appkit/hooks/transaction/use-watch-transactions.tsx diff --git a/demo/examples/src/appkit/hooks/wallets/use-address.tsx b/docs/examples/src/appkit/hooks/wallets/use-address.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/wallets/use-address.tsx rename to docs/examples/src/appkit/hooks/wallets/use-address.tsx diff --git a/demo/examples/src/appkit/hooks/wallets/use-connect.tsx b/docs/examples/src/appkit/hooks/wallets/use-connect.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/wallets/use-connect.tsx rename to docs/examples/src/appkit/hooks/wallets/use-connect.tsx diff --git a/demo/examples/src/appkit/hooks/wallets/use-connected-wallets.tsx b/docs/examples/src/appkit/hooks/wallets/use-connected-wallets.tsx similarity index 97% rename from demo/examples/src/appkit/hooks/wallets/use-connected-wallets.tsx rename to docs/examples/src/appkit/hooks/wallets/use-connected-wallets.tsx index 75c5bc24e..decf4f90e 100644 --- a/demo/examples/src/appkit/hooks/wallets/use-connected-wallets.tsx +++ b/docs/examples/src/appkit/hooks/wallets/use-connected-wallets.tsx @@ -18,7 +18,7 @@ export const UseConnectedWalletsExample = () => {
        {connectedWallets.map((wallet) => (
      • - {wallet.getAddress()} ({wallet.getNetwork().toString()}) + {wallet.getAddress()} ({wallet.getNetwork().chainId})
      • ))}
      diff --git a/demo/examples/src/appkit/hooks/wallets/use-connector-by-id.tsx b/docs/examples/src/appkit/hooks/wallets/use-connector-by-id.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/wallets/use-connector-by-id.tsx rename to docs/examples/src/appkit/hooks/wallets/use-connector-by-id.tsx diff --git a/demo/examples/src/appkit/hooks/wallets/use-connectors.tsx b/docs/examples/src/appkit/hooks/wallets/use-connectors.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/wallets/use-connectors.tsx rename to docs/examples/src/appkit/hooks/wallets/use-connectors.tsx diff --git a/demo/examples/src/appkit/hooks/wallets/use-disconnect.tsx b/docs/examples/src/appkit/hooks/wallets/use-disconnect.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/wallets/use-disconnect.tsx rename to docs/examples/src/appkit/hooks/wallets/use-disconnect.tsx diff --git a/demo/examples/src/appkit/hooks/wallets/use-selected-wallet.tsx b/docs/examples/src/appkit/hooks/wallets/use-selected-wallet.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/wallets/use-selected-wallet.tsx rename to docs/examples/src/appkit/hooks/wallets/use-selected-wallet.tsx diff --git a/demo/examples/src/appkit/hooks/wallets/wallets.test.tsx b/docs/examples/src/appkit/hooks/wallets/wallets.test.tsx similarity index 100% rename from demo/examples/src/appkit/hooks/wallets/wallets.test.tsx rename to docs/examples/src/appkit/hooks/wallets/wallets.test.tsx diff --git a/demo/examples/src/appkit/setup-react.tsx b/docs/examples/src/appkit/setup-react.tsx similarity index 100% rename from demo/examples/src/appkit/setup-react.tsx rename to docs/examples/src/appkit/setup-react.tsx diff --git a/demo/examples/src/appkit/setup.ts b/docs/examples/src/appkit/setup.ts similarity index 100% rename from demo/examples/src/appkit/setup.ts rename to docs/examples/src/appkit/setup.ts diff --git a/docs/examples/src/appkit/staking/staking-providers.test.ts b/docs/examples/src/appkit/staking/staking-providers.test.ts new file mode 100644 index 000000000..198dfe92b --- /dev/null +++ b/docs/examples/src/appkit/staking/staking-providers.test.ts @@ -0,0 +1,23 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { describe, it, expect } from 'vitest'; + +import { stakingProviderInitExample, stakingProviderRegisterExample } from './tonstakers'; + +describe('Staking provider examples', () => { + it('STAKING_PROVIDER_INIT initialises AppKit with Tonstakers registered', async () => { + const appKit = await stakingProviderInitExample(); + expect(appKit.stakingManager.hasProvider('tonstakers')).toBe(true); + }); + + it('STAKING_PROVIDER_REGISTER registers Tonstakers via the action', async () => { + const appKit = await stakingProviderRegisterExample(); + expect(appKit.stakingManager.hasProvider('tonstakers')).toBe(true); + }); +}); diff --git a/demo/examples/src/appkit/staking/staking-widget.tsx b/docs/examples/src/appkit/staking/staking-widget.tsx similarity index 100% rename from demo/examples/src/appkit/staking/staking-widget.tsx rename to docs/examples/src/appkit/staking/staking-widget.tsx diff --git a/demo/examples/src/appkit/staking/tonstakers.ts b/docs/examples/src/appkit/staking/tonstakers.ts similarity index 100% rename from demo/examples/src/appkit/staking/tonstakers.ts rename to docs/examples/src/appkit/staking/tonstakers.ts diff --git a/demo/examples/src/appkit/swap/dedust.ts b/docs/examples/src/appkit/swap/dedust.ts similarity index 100% rename from demo/examples/src/appkit/swap/dedust.ts rename to docs/examples/src/appkit/swap/dedust.ts diff --git a/demo/examples/src/appkit/swap/omniston.ts b/docs/examples/src/appkit/swap/omniston.ts similarity index 100% rename from demo/examples/src/appkit/swap/omniston.ts rename to docs/examples/src/appkit/swap/omniston.ts diff --git a/docs/examples/src/appkit/swap/swap-providers.test.ts b/docs/examples/src/appkit/swap/swap-providers.test.ts new file mode 100644 index 000000000..160a4d50d --- /dev/null +++ b/docs/examples/src/appkit/swap/swap-providers.test.ts @@ -0,0 +1,47 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { AppKit, Network } from '@ton/appkit'; + +import { dedustQuickStartExample } from './dedust'; +import { omnistonQuickStartExample, swapProviderInitExample, swapProviderRegisterExample } from './omniston'; + +describe('Swap provider examples', () => { + let appKit: AppKit; + + beforeEach(() => { + appKit = new AppKit({ + networks: { + [Network.mainnet().chainId]: {}, + }, + }); + }); + + it('DEDUST_QUICK_START registers the DeDust provider on AppKit', () => { + dedustQuickStartExample(appKit); + expect(appKit.swapManager.hasProvider('dedust')).toBe(true); + }); + + it('OMNISTON_QUICK_START registers the Omniston provider on AppKit', () => { + omnistonQuickStartExample(appKit); + expect(appKit.swapManager.hasProvider('omniston')).toBe(true); + }); + + it('SWAP_PROVIDER_INIT initialises AppKit with both swap providers registered', async () => { + const initialized = await swapProviderInitExample(); + expect(initialized.swapManager.hasProvider('dedust')).toBe(true); + expect(initialized.swapManager.hasProvider('omniston')).toBe(true); + }); + + it('SWAP_PROVIDER_REGISTER registers swap providers via the action', async () => { + const registered = await swapProviderRegisterExample(); + expect(registered.swapManager.hasProvider('dedust')).toBe(true); + expect(registered.swapManager.hasProvider('omniston')).toBe(true); + }); +}); diff --git a/demo/examples/src/appkit/swap/swap-widget.tsx b/docs/examples/src/appkit/swap/swap-widget.tsx similarity index 100% rename from demo/examples/src/appkit/swap/swap-widget.tsx rename to docs/examples/src/appkit/swap/swap-widget.tsx diff --git a/demo/examples/src/initialize.ts b/docs/examples/src/initialize.ts similarity index 100% rename from demo/examples/src/initialize.ts rename to docs/examples/src/initialize.ts diff --git a/demo/examples/src/jettons.ts b/docs/examples/src/jettons.ts similarity index 100% rename from demo/examples/src/jettons.ts rename to docs/examples/src/jettons.ts diff --git a/demo/examples/src/lib/wallet-kit-initialize-sample.ts b/docs/examples/src/lib/wallet-kit-initialize-sample.ts similarity index 100% rename from demo/examples/src/lib/wallet-kit-initialize-sample.ts rename to docs/examples/src/lib/wallet-kit-initialize-sample.ts diff --git a/demo/examples/src/lib/wallet-manifest.ts b/docs/examples/src/lib/wallet-manifest.ts similarity index 100% rename from demo/examples/src/lib/wallet-manifest.ts rename to docs/examples/src/lib/wallet-manifest.ts diff --git a/demo/examples/src/requests.ts b/docs/examples/src/requests.ts similarity index 99% rename from demo/examples/src/requests.ts rename to docs/examples/src/requests.ts index 160b690d2..0ce6f5f82 100644 --- a/demo/examples/src/requests.ts +++ b/docs/examples/src/requests.ts @@ -42,7 +42,7 @@ export async function main() { } // Query balance const balance = await wallet.getBalance(); - console.log('WalletBalance', wallet.getAddress(), balance.toString()); + console.log('WalletBalance', wallet.getAddress(), balance); // SAMPLE_END: BASIC_WALLET_OPERATIONS_1 } diff --git a/demo/examples/src/send-jettons.ts b/docs/examples/src/send-jettons.ts similarity index 100% rename from demo/examples/src/send-jettons.ts rename to docs/examples/src/send-jettons.ts diff --git a/demo/examples/src/send-nft.ts b/docs/examples/src/send-nft.ts similarity index 100% rename from demo/examples/src/send-nft.ts rename to docs/examples/src/send-nft.ts diff --git a/demo/examples/src/send-ton.ts b/docs/examples/src/send-ton.ts similarity index 100% rename from demo/examples/src/send-ton.ts rename to docs/examples/src/send-ton.ts diff --git a/demo/examples/src/ui-state-wiring.ts b/docs/examples/src/ui-state-wiring.ts similarity index 100% rename from demo/examples/src/ui-state-wiring.ts rename to docs/examples/src/ui-state-wiring.ts diff --git a/demo/examples/src/ui/render-connect-preview.tsx b/docs/examples/src/ui/render-connect-preview.tsx similarity index 100% rename from demo/examples/src/ui/render-connect-preview.tsx rename to docs/examples/src/ui/render-connect-preview.tsx diff --git a/demo/examples/src/ui/render-money-flow.tsx b/docs/examples/src/ui/render-money-flow.tsx similarity index 100% rename from demo/examples/src/ui/render-money-flow.tsx rename to docs/examples/src/ui/render-money-flow.tsx diff --git a/demo/examples/src/ui/render-sign-data-preview.tsx b/docs/examples/src/ui/render-sign-data-preview.tsx similarity index 100% rename from demo/examples/src/ui/render-sign-data-preview.tsx rename to docs/examples/src/ui/render-sign-data-preview.tsx diff --git a/demo/examples/src/ui/summarize-transaction.tsx b/docs/examples/src/ui/summarize-transaction.tsx similarity index 100% rename from demo/examples/src/ui/summarize-transaction.tsx rename to docs/examples/src/ui/summarize-transaction.tsx diff --git a/demo/examples/tsconfig.json b/docs/examples/tsconfig.json similarity index 100% rename from demo/examples/tsconfig.json rename to docs/examples/tsconfig.json diff --git a/demo/examples/vitest.config.ts b/docs/examples/vitest.config.ts similarity index 100% rename from demo/examples/vitest.config.ts rename to docs/examples/vitest.config.ts diff --git a/docs/reference-generator/package.json b/docs/reference-generator/package.json new file mode 100644 index 000000000..d8a3e054c --- /dev/null +++ b/docs/reference-generator/package.json @@ -0,0 +1,18 @@ +{ + "name": "@ton/reference-generator", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "Generates Mintlify-flavored API reference for @ton/appkit and @ton/appkit-react", + "scripts": { + "generate": "tsx src/index.ts", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "ts-morph": "^28.0.0" + }, + "devDependencies": { + "tsx": "^4.21.0", + "typescript": "~5.9.3" + } +} diff --git a/docs/reference-generator/src/collect.ts b/docs/reference-generator/src/collect.ts new file mode 100644 index 000000000..57c58fa63 --- /dev/null +++ b/docs/reference-generator/src/collect.ts @@ -0,0 +1,235 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { Node, Project, SymbolFlags } from 'ts-morph'; +import type { JSDoc, SourceFile, Symbol as TsSymbol } from 'ts-morph'; + +export interface CollectedSymbol { + name: string; + /** Original declaration — used by extract.ts for shape (fields, members, signature). */ + declaration: Node; + /** Declaration in the local package whose JSDoc tags drive this symbol's metadata. + * Equals `declaration` for symbols defined in this package, or the local + * alias-export when the symbol is re-exported from another workspace + * package via `@extract`. */ + metadataDeclaration: Node; + /** True when the symbol arrived via `@extract` re-export from another package. */ + extracted: boolean; + sourceFile: SourceFile; + /** Path relative to the package's src/ directory. e.g. "actions/balances/get-balance-by-address.ts" */ + sourcePath: string; + /** Value of the `@section` JSDoc tag. Forms the top-level grouping (e.g. Action, Class, Type). */ + section: string | null; + /** Value of the `@category` JSDoc tag. Forms the second-level grouping (e.g. Balances, Signing). */ + category: string | null; +} + +export interface CollectOptions { + packagePath: string; +} + +export function collectPublicApi(options: CollectOptions): CollectedSymbol[] { + const { packagePath } = options; + const tsConfigFilePath = join(packagePath, 'tsconfig.json'); + + const project = new Project({ tsConfigFilePath }); + + const entryAbsPaths = readEntryPaths(packagePath); + const seenRealSymbols = new Set(); + const collected: CollectedSymbol[] = []; + + for (const entryAbsPath of entryAbsPaths) { + const sourceFile = project.getSourceFile(entryAbsPath); + if (!sourceFile) { + console.warn(`[collect] Entry not found in project: ${entryAbsPath}`); + continue; + } + + const srcPrefix = `${packagePath}/src/`; + + for (const exportSymbol of sourceFile.getExportSymbols()) { + const real = unwrapAlias(exportSymbol); + if (seenRealSymbols.has(real)) continue; + + const realDecl = real.getDeclarations()[0]; + if (!realDecl) continue; + + const realDeclPath = realDecl.getSourceFile().getFilePath(); + const realInPkg = realDeclPath.startsWith(srcPrefix); + + // Where to read JSDoc tags from. Normally that's the declaration + // itself; for cross-package re-exports we read from the alias + // declaration in our package (the `export { … } from 'pkg'` line) + // and require an explicit `@extract` opt-in there. When a symbol + // is re-exported from multiple places, prefer the alias that + // carries `@extract` + `@public` so the chosen metadata is the + // documented one, regardless of traversal order. + let metadataDecl: Node = realDecl; + let extracted = false; + + if (!realInPkg) { + const annotated = findAnnotatedAlias(exportSymbol, srcPrefix); + if (!annotated) continue; + metadataDecl = annotated; + extracted = true; + } else if (!hasPublicTag(metadataDecl)) { + continue; + } + + seenRealSymbols.add(real); + + const sourcePath = realInPkg + ? realDeclPath.slice(srcPrefix.length) + : metadataDecl.getSourceFile().getFilePath().slice(srcPrefix.length); + + collected.push({ + name: exportSymbol.getName(), + declaration: realDecl, + metadataDeclaration: metadataDecl, + extracted, + sourceFile: realDecl.getSourceFile(), + sourcePath, + section: readTagValue(metadataDecl, 'section'), + category: readTagValue(metadataDecl, 'category'), + }); + } + } + + return collected; +} + +export function getJsDocs(decl: Node): JSDoc[] { + if (Node.isVariableDeclaration(decl)) { + return decl.getVariableStatement()?.getJsDocs() ?? []; + } + if (Node.isExportSpecifier(decl)) { + // JSDoc lives on the parent ExportDeclaration (`/** … */ export { Foo } from '…'`). + // ExportDeclaration is not JSDocable in ts-morph's mixin, so pull the JSDoc nodes from its children. + return decl + .getExportDeclaration() + .getChildren() + .filter((c): c is JSDoc => Node.isJSDoc(c)); + } + return Node.isJSDocable(decl) ? decl.getJsDocs() : []; +} + +function hasPublicTag(decl: Node): boolean { + for (const doc of getJsDocs(decl)) { + for (const tag of doc.getTags()) { + if (tag.getTagName() === 'public') return true; + } + } + return false; +} + +function hasExtractTag(decl: Node): boolean { + for (const doc of getJsDocs(decl)) { + for (const tag of doc.getTags()) { + if (tag.getTagName() === 'extract') return true; + } + } + return false; +} + +function readTagValue(decl: Node, tagName: string): string | null { + for (const doc of getJsDocs(decl)) { + for (const tag of doc.getTags()) { + if (tag.getTagName() !== tagName) continue; + const text = tag.getCommentText()?.trim(); + if (text) return text; + } + } + return null; +} + +function unwrapAlias(symbol: TsSymbol): TsSymbol { + let current = symbol; + let next = current.getAliasedSymbol(); + while (next) { + current = next; + next = current.getAliasedSymbol(); + } + return current; +} + +/** + * Walks the alias chain looking for an alias declaration in our package whose + * parent `export { … } from '…'` carries both `@extract` and `@public`. + * + * `exportSymbol.getDeclarations()` only returns the immediate alias hop, so when + * a symbol is re-exported through multiple files (root → core/network → walletkit + * leaf) we have to follow each ExportSpecifier's own immediately-aliased symbol + * to find an annotated link further down the chain. + */ +function findAnnotatedAlias(exportSymbol: TsSymbol, srcPrefix: string): Node | null { + const visited = new Set(); + let cursor: TsSymbol | undefined = exportSymbol; + while (cursor !== undefined && !visited.has(cursor)) { + const node: TsSymbol = cursor; + visited.add(node); + + const localDecls = node.getDeclarations().filter((d) => d.getSourceFile().getFilePath().startsWith(srcPrefix)); + const annotated = localDecls.find((d) => hasExtractTag(d) && hasPublicTag(d)); + if (annotated) return annotated; + + // Step one hop down the alias chain. `getImmediatelyAliasedSymbol` only + // works on alias-flagged symbols (export specifiers, imports, namespace + // imports); it asserts otherwise. Bail out cleanly when we've hit the + // real declaration and there's nowhere further to walk. + const isAlias = (node.getFlags() & SymbolFlags.Alias) !== 0; + cursor = isAlias ? node.getImmediatelyAliasedSymbol() : undefined; + } + return null; +} + +interface ConditionalExport { + [condition: string]: string | ConditionalExport; +} +type ExportEntry = string | ConditionalExport; + +function readEntryPaths(packagePath: string): string[] { + const pkg = JSON.parse(readFileSync(join(packagePath, 'package.json'), 'utf-8')) as { + exports?: Record; + }; + const exports = pkg.exports ?? {}; + const entries = new Set(); + + for (const [key, value] of Object.entries(exports)) { + if (key.endsWith('.css')) continue; + + const distPath = pickEntryPath(value); + if (!distPath) continue; + + const srcRelative = distPath + .replace(/^\.\//, '') + .replace(/^dist\/(esm|cjs|types)\//, 'src/') + .replace(/\.d\.ts$/, '.ts') + .replace(/\.js$/, '.ts'); + + entries.add(join(packagePath, srcRelative)); + } + + return [...entries]; +} + +function pickEntryPath(value: ExportEntry): string | null { + if (typeof value === 'string') { + return value.endsWith('.js') || value.endsWith('.d.ts') ? value : null; + } + if (value && typeof value === 'object') { + const candidates = [value['import'], value['default'], value['types']]; + for (const c of candidates) { + if (typeof c === 'string') return pickEntryPath(c); + if (c && typeof c === 'object') return pickEntryPath(c); + } + } + return null; +} diff --git a/docs/reference-generator/src/extract.ts b/docs/reference-generator/src/extract.ts new file mode 100644 index 000000000..6d0f5705f --- /dev/null +++ b/docs/reference-generator/src/extract.ts @@ -0,0 +1,982 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { Node, TypeFormatFlags } from 'ts-morph'; +import type { + ClassDeclaration, + EnumDeclaration, + FunctionDeclaration, + InterfaceDeclaration, + JSDoc, + JSDocParameterTag, + ObjectLiteralExpression, + ParameterDeclaration, + Type, + TypeAliasDeclaration, + VariableDeclaration, +} from 'ts-morph'; + +import { getJsDocs } from './collect'; +import type { CollectedSymbol } from './collect'; + +export type SymbolKind = 'function' | 'component' | 'componentNamespace' | 'type' | 'class'; + +export const VALID_CATEGORIES = ['Class', 'Action', 'Hook', 'Component', 'Type', 'Constants'] as const; +export type ValidCategory = (typeof VALID_CATEGORIES)[number]; + +export interface ParamRow { + name: string; + typeText: string; + /** When set, the renderer uses this name (link if documented) instead of `typeText`. */ + typeOverride: string | null; + required: boolean; + description: string | null; +} + +export interface ExtractedFunction { + kind: 'function'; + name: string; + sourcePath: string; + section: string; + category: string; + summary: string | null; + params: ParamRow[]; + returnTypeText: string; + returnTypeOverride: string | null; + returnDescription: string | null; + examples: string[]; + samples: string[]; +} + +export interface ExtractedComponent { + kind: 'component'; + name: string; + sourcePath: string; + section: string; + category: string; + summary: string | null; + props: ParamRow[]; + examples: string[]; + samples: string[]; +} + +export interface ExtractedNamespaceComponent { + kind: 'componentNamespace'; + name: string; + sourcePath: string; + section: string; + category: string; + summary: string | null; + members: { name: string; props: ParamRow[]; summary: string | null }[]; + examples: string[]; + samples: string[]; +} + +export interface ExtractedType { + kind: 'type'; + name: string; + sourcePath: string; + section: string; + category: string; + summary: string | null; + fields: ParamRow[] | null; + typeText: string | null; + /** True for `const X = ...` declarations; renderer uses `const`-form code block. */ + isConstant: boolean; +} + +export interface ExtractedClass { + kind: 'class'; + name: string; + sourcePath: string; + section: string; + category: string; + summary: string | null; + constructorParams: ParamRow[] | null; + examples: string[]; + samples: string[]; +} + +export type Extracted = + | ExtractedFunction + | ExtractedComponent + | ExtractedNamespaceComponent + | ExtractedType + | ExtractedClass; + +const FORMAT_FLAGS = + TypeFormatFlags.NoTruncation | + TypeFormatFlags.UseAliasDefinedOutsideCurrentScope | + TypeFormatFlags.WriteArrayAsGenericType; + +type ExtractedWithoutMeta = + | Omit + | Omit + | Omit + | Omit + | Omit; + +export function extract(collected: CollectedSymbol): Extracted { + const { name, declaration, metadataDeclaration, sourcePath } = collected; + const category = collected.category ?? ''; + + if (!isValidCategory(category)) { + throw new Error(`[${name}] Invalid @category "${category}". Allowed values: ${VALID_CATEGORIES.join(', ')}.`); + } + + const inner = extractByCategory(category, name, declaration, sourcePath); + const section = collected.section ?? ''; + + // For @extract re-exports, prefer the JSDoc summary from the local export comment + // over (often missing) JSDoc on the imported declaration in the other package. + const metadataSummary = + metadataDeclaration !== declaration ? readSummary(pickJsDoc(getJsDocs(metadataDeclaration))) : null; + if (metadataSummary && 'summary' in inner) { + return { ...inner, section, category, summary: metadataSummary } as Extracted; + } + + return { ...inner, section, category } as Extracted; +} + +function isValidCategory(value: string): value is ValidCategory { + return (VALID_CATEGORIES as readonly string[]).includes(value); +} + +function extractByCategory( + category: ValidCategory, + name: string, + declaration: Node, + sourcePath: string, +): ExtractedWithoutMeta { + switch (category) { + case 'Type': + if (Node.isInterfaceDeclaration(declaration) || Node.isTypeAliasDeclaration(declaration)) { + return extractType(name, declaration, sourcePath); + } + throw mismatch(name, category, 'interface or type alias'); + + case 'Constants': + if (Node.isVariableDeclaration(declaration) || Node.isEnumDeclaration(declaration)) { + return extractType(name, declaration, sourcePath); + } + throw mismatch(name, category, 'const or enum declaration'); + + case 'Class': + if (Node.isClassDeclaration(declaration)) { + return extractClass(name, declaration, sourcePath); + } + if (Node.isTypeAliasDeclaration(declaration) && hasExtractTag(declaration)) { + const expanded = expandClassThroughExtract(name, declaration, sourcePath); + if (expanded) return expanded; + } + throw mismatch(name, category, 'class declaration or @extract type alias targeting a class'); + + case 'Action': + case 'Hook': + if (Node.isFunctionDeclaration(declaration)) { + return extractFunctionLike(declaration, name, sourcePath); + } + if (Node.isVariableDeclaration(declaration)) { + return extractVariableFunction(declaration, name, sourcePath); + } + throw mismatch(name, category, 'function declaration or arrow/function variable'); + + case 'Component': + if (Node.isVariableDeclaration(declaration)) { + const init = declaration.getInitializer(); + const membersLiteral = resolveNamespaceMembersLiteral(init); + if (membersLiteral) { + return extractNamespaceComponent(name, declaration, membersLiteral, sourcePath); + } + return extractVariableAsComponent(declaration, name, sourcePath); + } + if (Node.isFunctionDeclaration(declaration)) { + return extractFunctionAsComponent(declaration, name, sourcePath); + } + throw mismatch(name, category, 'function or variable declaration'); + } +} + +/** + * Returns the object-literal carrying compound members, or null when the + * initializer doesn't look like a compound. Two shapes are recognized: + * - bare `{ Member: ... }` literal (the simple compound pattern) + * - `Object.assign(Root, { Member: ... })` — used when the root needs to also be + * callable as a React component (e.g. `Input`, `CurrencyItem`). + */ +function resolveNamespaceMembersLiteral(init: Node | undefined): ObjectLiteralExpression | null { + if (!init) return null; + if (Node.isObjectLiteralExpression(init)) return init; + if (Node.isCallExpression(init)) { + const expr = init.getExpression(); + const callee = expr.getText(); + if (callee !== 'Object.assign') return null; + const args = init.getArguments(); + const literal = args.find((arg) => Node.isObjectLiteralExpression(arg)); + return literal && Node.isObjectLiteralExpression(literal) ? literal : null; + } + return null; +} + +function mismatch(name: string, category: ValidCategory, expected: string): Error { + return new Error(`[${name}] @category ${category} requires the symbol to be a ${expected}.`); +} + +function extractFunctionLike( + decl: FunctionDeclaration, + name: string, + sourcePath: string, +): Omit { + const jsdoc = pickJsDoc(decl.getJsDocs()); + const summary = readSummary(jsdoc); + const paramTags = readParamTags(jsdoc); + const returnInfo = readReturnInfo(jsdoc); + const examples = readExamples(jsdoc); + const samples = readSamples(jsdoc); + const expandNames = readExpandNames(jsdoc); + + const params = expandParameters(decl.getParameters(), decl, paramTags, expandNames); + const fnTypeParams = collectTypeParamDefaults(decl); + const rawReturnNode = decl.getReturnTypeNode()?.getText(); + const returnTypeText = rawReturnNode + ? collapseWhitespace(substituteTypeParams(rawReturnNode, fnTypeParams)) + : formatType(decl.getReturnType(), decl); + + return { + kind: 'function', + name, + sourcePath, + summary, + params, + returnTypeText, + returnTypeOverride: returnInfo.typeOverride, + returnDescription: returnInfo.description, + examples, + samples, + }; +} + +function extractVariableFunction( + decl: VariableDeclaration, + name: string, + sourcePath: string, +): Omit { + const stmt = decl.getVariableStatement(); + const jsdoc = pickJsDoc(stmt?.getJsDocs() ?? []); + const summary = readSummary(jsdoc); + const paramTags = readParamTags(jsdoc); + const returnInfo = readReturnInfo(jsdoc); + const examples = readExamples(jsdoc); + const samples = readSamples(jsdoc); + const expandNames = readExpandNames(jsdoc); + + const init = decl.getInitializer(); + + // Inline arrow / function-expression: read parameters and return type + // straight from the AST so authors get @sample-based examples and `@expand` + // flattening. + if (init && (Node.isArrowFunction(init) || Node.isFunctionExpression(init))) { + const params = expandParameters(init.getParameters(), decl, paramTags, expandNames); + const fnTypeParams = collectTypeParamDefaults(init); + const rawReturnNode = init.getReturnTypeNode()?.getText(); + const returnTypeText = rawReturnNode + ? collapseWhitespace(substituteTypeParams(rawReturnNode, fnTypeParams)) + : formatType(init.getReturnType(), decl); + + return { + kind: 'function', + name, + sourcePath, + summary, + params, + returnTypeText, + returnTypeOverride: returnInfo.typeOverride, + returnDescription: returnInfo.description, + examples, + samples, + }; + } + + // No inline initializer (e.g., `declare const fn: (...) => ...` re-exported + // from walletkit through `@extract`). Fall back to the variable's call + // signature — we lose parameter-name accuracy in some edge cases but it's + // the only signal available. + const callSig = decl.getType().getCallSignatures()[0]; + if (callSig) { + const sigParams = callSig.getParameters(); + const params: ParamRow[] = sigParams.map((p) => { + const valueDecl = p.getValueDeclaration(); + const paramName = p.getName(); + const tagInfo = paramTags.get(paramName); + const required = + valueDecl && Node.isParameterDeclaration(valueDecl) + ? !valueDecl.hasQuestionToken() && !valueDecl.hasInitializer() && !valueDecl.isRestParameter() + : true; + const typeText = + valueDecl && Node.isParameterDeclaration(valueDecl) + ? collapseWhitespace( + valueDecl.getTypeNode()?.getText() ?? formatType(p.getTypeAtLocation(decl), decl), + ) + : formatType(p.getTypeAtLocation(decl), decl); + return { + name: paramName, + typeText, + typeOverride: tagInfo?.typeOverride ?? null, + required, + description: tagInfo?.description ?? null, + }; + }); + const returnTypeText = formatType(callSig.getReturnType(), decl); + return { + kind: 'function', + name, + sourcePath, + summary, + params, + returnTypeText, + returnTypeOverride: returnInfo.typeOverride, + returnDescription: returnInfo.description, + examples, + samples, + }; + } + + return { + kind: 'function', + name, + sourcePath, + summary, + params: [], + returnTypeText: 'unknown', + returnTypeOverride: returnInfo.typeOverride, + returnDescription: returnInfo.description, + examples, + samples, + }; +} + +function extractFunctionAsComponent( + decl: FunctionDeclaration, + name: string, + sourcePath: string, +): Omit { + const jsdoc = pickJsDoc(decl.getJsDocs()); + const summary = readSummary(jsdoc); + const examples = readExamples(jsdoc); + const samples = readSamples(jsdoc); + const props = expandComponentProps(decl.getParameters(), decl); + return { kind: 'component', name, sourcePath, summary, props, examples, samples }; +} + +function extractVariableAsComponent( + decl: VariableDeclaration, + name: string, + sourcePath: string, +): Omit { + const stmt = decl.getVariableStatement(); + const jsdoc = pickJsDoc(stmt?.getJsDocs() ?? []); + const summary = readSummary(jsdoc); + const examples = readExamples(jsdoc); + const samples = readSamples(jsdoc); + + const init = decl.getInitializer(); + let propsType: Type | null = null; + + if (init && (Node.isArrowFunction(init) || Node.isFunctionExpression(init))) { + const params = init.getParameters(); + if (params.length > 0) propsType = params[0].getType(); + } else if (init && Node.isCallExpression(init)) { + // Wrappers like `forwardRef((props, ref) => ...)` or `memo((props) => ...)` — + // the variable's resolved type buries the real props inside React's helper + // types, so read the props from the render function arg instead. + propsType = readPropsFromComponentWrapper(init); + } else { + const callSig = decl.getType().getCallSignatures()[0]; + const propsParam = callSig?.getParameters()[0]; + if (propsParam) { + propsType = propsParam.getValueDeclaration()?.getType() ?? null; + } + } + + const props = propsType ? readPropsFromType(propsType, decl) : []; + return { kind: 'component', name, sourcePath, summary, props, examples, samples }; +} + +function readPropsFromComponentWrapper(call: Node): Type | null { + if (!Node.isCallExpression(call)) return null; + const firstArg = call.getArguments()[0]; + if (!firstArg) return null; + if (Node.isArrowFunction(firstArg) || Node.isFunctionExpression(firstArg)) { + const params = firstArg.getParameters(); + if (params.length > 0) return params[0].getType(); + } + return null; +} + +function extractNamespaceComponent( + name: string, + decl: VariableDeclaration, + init: ObjectLiteralExpression, + sourcePath: string, +): Omit { + const stmt = decl.getVariableStatement(); + const jsdoc = pickJsDoc(stmt?.getJsDocs() ?? []); + const summary = readSummary(jsdoc); + const examples = readExamples(jsdoc); + const samples = readSamples(jsdoc); + + const members: ExtractedNamespaceComponent['members'] = []; + for (const prop of init.getProperties()) { + if (!Node.isPropertyAssignment(prop) && !Node.isShorthandPropertyAssignment(prop)) continue; + const memberName = prop.getName(); + const memberType = prop.getType(); + const callSig = memberType.getCallSignatures()[0]; + const propsParam = callSig?.getParameters()[0]; + const propsType = propsParam?.getValueDeclaration()?.getType() ?? null; + const props = propsType ? readPropsFromType(propsType, decl) : []; + const memberSummary = readLeadingJsDocSummary(prop); + members.push({ name: memberName, props, summary: memberSummary }); + } + + return { kind: 'componentNamespace', name, sourcePath, summary, members, examples, samples }; +} + +function extractType( + name: string, + decl: InterfaceDeclaration | TypeAliasDeclaration | VariableDeclaration | EnumDeclaration, + sourcePath: string, +): Omit { + if (Node.isVariableDeclaration(decl)) { + const stmt = decl.getVariableStatement(); + const jsdoc = pickJsDoc(stmt?.getJsDocs() ?? []); + const summary = readSummary(jsdoc); + const init = decl.getInitializer(); + const typeText = init ? init.getText() : decl.getType().getText(decl, FORMAT_FLAGS); + return { kind: 'type', name, sourcePath, summary, fields: null, typeText, isConstant: true }; + } + + if (Node.isEnumDeclaration(decl)) { + const summary = readSummary(pickJsDoc(decl.getJsDocs())); + const fields: ParamRow[] = decl.getMembers().map((member) => { + const init = member.getInitializer(); + const valueText = init ? init.getText() : 'auto'; + const desc = readSummary(pickJsDoc(member.getJsDocs())); + return { + name: member.getName(), + typeText: valueText, + typeOverride: null, + required: true, + description: desc, + }; + }); + return { kind: 'type', name, sourcePath, summary, fields, typeText: null, isConstant: true }; + } + + const jsdoc = pickJsDoc(decl.getJsDocs()); + const summary = readSummary(jsdoc); + + if (Node.isTypeAliasDeclaration(decl) && hasExtractTag(decl)) { + const expanded = expandThroughExtract(name, decl, sourcePath); + if (expanded) { + return { ...expanded, summary: summary ?? expanded.summary }; + } + } + + if (Node.isInterfaceDeclaration(decl)) { + const fields = readPropsFromType(decl.getType(), decl); + return { kind: 'type', name, sourcePath, summary, fields, typeText: null, isConstant: false }; + } + + const typeNode = decl.getTypeNode(); + if (typeNode && Node.isTypeLiteral(typeNode)) { + const fields = readPropsFromType(decl.getType(), decl); + if (fields.length > 0) { + return { kind: 'type', name, sourcePath, summary, fields, typeText: null, isConstant: false }; + } + // Type literal without named props (e.g. only an index signature) — fall back to the source text. + return { + kind: 'type', + name, + sourcePath, + summary, + fields: null, + typeText: typeNode.getText(), + isConstant: false, + }; + } + + // Resolved-shape intersection — `type X = A & B` or `type X = SomeAlias` + // that itself resolves to one. Flatten into a fields table when the merged + // properties form a clean object bag (catches our own `address`/`network` + // plus the `query` / `mutation` catch-all from `QueryParameter` / + // `MutationParameter` without hand-rolling a mirror interface). + const resolvedType = decl.getType(); + if (resolvedType.isIntersection() && !resolvedType.isUnion()) { + const fields = readPropsFromType(resolvedType, decl); + if (fields.length > 0) { + return { kind: 'type', name, sourcePath, summary, fields, typeText: null, isConstant: false }; + } + } + + const typeText = typeNode ? typeNode.getText() : resolvedType.getText(decl, FORMAT_FLAGS); + return { kind: 'type', name, sourcePath, summary, fields: null, typeText, isConstant: false }; +} + +function hasExtractTag(decl: Node): boolean { + if (!Node.isJSDocable(decl)) return false; + for (const doc of decl.getJsDocs()) { + for (const tag of doc.getTags()) { + if (tag.getTagName() === 'extract') return true; + } + } + return false; +} + +/** + * Resolves a `@extract`-tagged type alias to its underlying interface or type + * declaration (typically in another package) and reuses its shape. Returns + * null if the alias does not point at something extractable. + */ +function expandClassThroughExtract( + name: string, + decl: TypeAliasDeclaration, + sourcePath: string, +): Omit | null { + const targetDecl = resolveExtractTarget(decl); + if (!targetDecl || !Node.isClassDeclaration(targetDecl)) return null; + const aliasJsDoc = pickJsDoc(decl.getJsDocs()); + const aliasSummary = readSummary(aliasJsDoc); + const inner = extractClass(name, targetDecl, sourcePath); + return { ...inner, summary: aliasSummary ?? inner.summary }; +} + +function expandThroughExtract( + name: string, + decl: TypeAliasDeclaration, + sourcePath: string, +): Omit | null { + const targetDecl = resolveExtractTarget(decl); + if (targetDecl && (Node.isInterfaceDeclaration(targetDecl) || Node.isTypeAliasDeclaration(targetDecl))) { + return extractType(name, targetDecl, sourcePath); + } + // No named target outside this declaration — fall back to the structural form. + const typeText = decl.getType().getText(decl, FORMAT_FLAGS); + return { kind: 'type', name, sourcePath, summary: null, fields: null, typeText, isConstant: false }; +} + +/** + * Resolves a `@extract`-tagged type alias to the underlying declaration. + * Returns null if the resolution would loop back to the alias itself + * (which can happen when ts-morph's symbol resolver returns the alias node + * for re-exported types — guarding here prevents infinite recursion). + */ +function resolveExtractTarget(decl: TypeAliasDeclaration): Node | null { + // Prefer the type-node's identifier when the alias is `type X = Y` or + // `type X = Y<…>` — `getDefinitionNodes()` follows TypeScript's resolver + // through `import type` aliases all the way to the original class / + // interface / type declaration, even across packages. + const typeNode = decl.getTypeNode(); + if (typeNode && Node.isTypeReference(typeNode)) { + const typeName = typeNode.getTypeName(); + if (Node.isIdentifier(typeName)) { + for (const definition of typeName.getDefinitionNodes()) { + if (definition === decl) continue; + if ( + Node.isClassDeclaration(definition) || + Node.isInterfaceDeclaration(definition) || + Node.isTypeAliasDeclaration(definition) + ) { + return definition; + } + } + } + } + // Fallback: use the resolved type's symbol chain (works for inline types). + const aliasedType = decl.getType(); + let symbol = aliasedType.getAliasSymbol() ?? aliasedType.getSymbol(); + if (!symbol) return null; + let next = symbol.getAliasedSymbol(); + while (next) { + symbol = next; + next = symbol.getAliasedSymbol(); + } + const targetDecl = symbol.getDeclarations()[0]; + if (!targetDecl || targetDecl === decl) return null; + return targetDecl; +} + +function extractClass( + name: string, + decl: ClassDeclaration, + sourcePath: string, +): Omit { + const jsdoc = pickJsDoc(decl.getJsDocs()); + const summary = readSummary(jsdoc); + const examples = readExamples(jsdoc); + const samples = readSamples(jsdoc); + const ctor = decl.getConstructors()[0]; + if (!ctor) { + return { kind: 'class', name, sourcePath, summary, constructorParams: null, examples, samples }; + } + const ctorJsDoc = pickJsDoc(ctor.getJsDocs()); + const ctorParamTags = readParamTags(ctorJsDoc); + const ctorExpandNames = readExpandNames(ctorJsDoc); + const constructorParams = expandParameters(ctor.getParameters(), decl, ctorParamTags, ctorExpandNames); + return { kind: 'class', name, sourcePath, summary, constructorParams, examples, samples }; +} + +function expandParameters( + params: ParameterDeclaration[], + contextNode: Node, + paramTags: Map, + expandNames: Set, +): ParamRow[] { + const rows: ParamRow[] = []; + + const fnTypeParams = collectTypeParamDefaults(contextNode); + + for (const param of params) { + const paramName = param.getName(); + const rawParamType = param.getType(); + // Optional params surface as `T | undefined` in their resolved type — peel that + // back to `T` so `@expand` flattening sees the underlying object shape. + const paramType = stripUndefinedFromUnion(rawParamType); + const required = !param.hasQuestionToken() && !param.hasInitializer() && !param.isRestParameter(); + const tagInfo = paramTags.get(paramName); + const rawSyntactic = param.getTypeNode()?.getText(); + const paramSyntactic = rawSyntactic + ? collapseWhitespace(substituteTypeParams(rawSyntactic, fnTypeParams)) + : formatType(paramType, contextNode); + + const shouldFlatten = expandNames.has(paramName) && isFlattenableObjectType(paramType); + + if (shouldFlatten) { + rows.push({ + name: paramName, + typeText: paramSyntactic, + typeOverride: tagInfo?.typeOverride ?? null, + required, + description: tagInfo?.description ?? null, + }); + const declaredFields = readPropsFromType(paramType, contextNode); + for (const field of declaredFields) { + const tagKey = `${paramName}.${field.name}`; + const fieldTagInfo = paramTags.get(tagKey); + rows.push({ + ...field, + name: `${paramName}.${field.name}`, + typeOverride: fieldTagInfo?.typeOverride ?? field.typeOverride, + description: field.description ?? fieldTagInfo?.description ?? null, + }); + } + continue; + } + + rows.push({ + name: paramName, + typeText: paramSyntactic, + typeOverride: tagInfo?.typeOverride ?? null, + required, + description: tagInfo?.description ?? null, + }); + } + + return rows; +} + +function expandComponentProps(params: ParameterDeclaration[], contextNode: Node): ParamRow[] { + if (params.length === 0) return []; + const propsParam = params[0]; + return readPropsFromType(propsParam.getType(), contextNode); +} + +function readPropsFromType(type: Type, contextNode: Node): ParamRow[] { + const rows: ParamRow[] = []; + for (const prop of type.getProperties()) { + const propName = prop.getName(); + if (propName.startsWith('__@')) continue; + + const valueDecl = prop.getValueDeclaration() ?? prop.getDeclarations()[0]; + if (!valueDecl) continue; + + const declPath = valueDecl.getSourceFile().getFilePath(); + if (declPath.includes('/node_modules/')) continue; + if (declPath.includes('/typescript/lib/lib.')) continue; + + const propType = prop.getTypeAtLocation(contextNode); + const optional = (prop.getFlags() & 16777216) !== 0; // ts.SymbolFlags.Optional + const description = readPropertyJsDoc(valueDecl); + // Opt-in property-level type override: `@typeAs Name` on the field's JSDoc swaps the rendered + // Type cell for a chip pointing at `Name`. Useful when the inferred type is a noisy generic + // alias that already has its own short documented name (e.g. `QueryOptionsOverride`). + const typeOverride = readPropertyTypeAs(valueDecl); + const rawSyntactic = + Node.isPropertySignature(valueDecl) || Node.isPropertyDeclaration(valueDecl) + ? valueDecl.getTypeNode()?.getText() + : undefined; + const syntacticType = rawSyntactic + ? collapseWhitespace(substituteTypeParams(rawSyntactic, collectTypeParamDefaults(valueDecl))) + : formatType(propType, contextNode); + rows.push({ + name: prop.getName(), + typeText: syntacticType, + typeOverride, + required: !optional, + description, + }); + } + return rows; +} + +function readPropertyTypeAs(node: Node): string | null { + if (!Node.isJSDocable(node)) return null; + for (const doc of node.getJsDocs()) { + for (const tag of doc.getTags()) { + if (tag.getTagName() !== 'typeAs') continue; + const text = tag.getCommentText()?.trim(); + if (text) return text; + } + } + return null; +} + +/** + * Walks up to the nearest declaration with type parameters (interface, type + * alias, class, function) and returns a map from each parameter's name to its + * `Name = Default` annotation — falling back to `Name = any` when no default + * was declared. + * + * Used to expand generics in property and parameter type texts so readers see + * both the original placeholder and what it falls back to. `metadata: TMetadata` + * becomes `metadata: TMetadata = unknown`, and `Promise` becomes + * `Promise` — preserving the slot name the user can + * substitute by passing an explicit type argument. + */ +function collectTypeParamDefaults(start: Node): Map { + const map = new Map(); + let cursor: Node | undefined = start; + while (cursor) { + if ( + Node.isInterfaceDeclaration(cursor) || + Node.isTypeAliasDeclaration(cursor) || + Node.isClassDeclaration(cursor) || + Node.isFunctionDeclaration(cursor) || + Node.isMethodSignature(cursor) || + Node.isMethodDeclaration(cursor) || + Node.isFunctionExpression(cursor) || + Node.isArrowFunction(cursor) + ) { + for (const tp of cursor.getTypeParameters()) { + const name = tp.getName(); + if (map.has(name)) continue; + const def = tp.getDefault()?.getText() ?? 'any'; + map.set(name, `${name} = ${def}`); + } + } + cursor = cursor.getParent(); + } + return map; +} + +function substituteTypeParams(typeText: string, params: Map): string { + if (params.size === 0) return typeText; + const names = [...params.keys()].sort((a, b) => b.length - a.length); + const pattern = new RegExp(`\\b(${names.map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})\\b`, 'g'); + return typeText.replace(pattern, (m) => params.get(m) ?? m); +} + +function isFlattenableObjectType(type: Type): boolean { + if (type.isUnion()) return false; + // Intersections like `Params & { providerId?: string }` resolve to a clean property bag — + // flattening them is fine as long as `getProperties()` returns something usable. + if (type.isIntersection()) return type.getProperties().length > 0; + if (!type.isObject()) return false; + if (type.getCallSignatures().length > 0) return false; + if (type.getConstructSignatures().length > 0) return false; + return type.getProperties().length > 0; +} + +function stripUndefinedFromUnion(type: Type): Type { + if (!type.isUnion()) return type; + const nonUndefined = type.getUnionTypes().filter((t) => !t.isUndefined() && !t.isNull()); + return nonUndefined.length === 1 ? nonUndefined[0] : type; +} + +function formatType(type: Type, contextNode: Node): string { + return type.getText(contextNode, FORMAT_FLAGS).replace(/\s+/g, ' '); +} + +/** + * Collapses runs of whitespace in a syntactic type text — turns indented inline object literals + * (e.g. `{ [key: string]: unknown; }`) into single-line readable chips. + */ +function collapseWhitespace(text: string): string { + return text.replace(/\s+/g, ' '); +} + +function pickJsDoc(jsDocs: JSDoc[]): JSDoc | null { + return jsDocs.length > 0 ? jsDocs[jsDocs.length - 1] : null; +} + +/** + * Read the leading `/** ... *\/` JSDoc-style comment attached to a property + * assignment inside an object literal. ts-morph's `PropertyAssignment` is not + * JSDocable, so we walk the raw leading-comment trivia. + */ +function readLeadingJsDocSummary(prop: Node): string | null { + for (const cr of prop.getLeadingCommentRanges()) { + const text = cr.getText(); + if (!text.startsWith('/**')) continue; + const inner = text + .replace(/^\/\*\*+/, '') + .replace(/\*+\/$/, '') + .split('\n') + .map((line) => line.replace(/^\s*\*\s?/, '')) + .join('\n') + .trim(); + if (inner) return sanitizeJsDocText(inner); + } + return null; +} + +function readSummary(jsdoc: JSDoc | null): string | null { + if (!jsdoc) return null; + const desc = sanitizeJsDocText(jsdoc.getDescription()); + if (!desc) return null; + // ts-morph occasionally attaches the file-level license header to the first + // declaration in a file when nothing else sits between them. Skip those — + // there is never a real description that begins with "Copyright (c)". + if (/^\s*Copyright\s*\(c\)/i.test(desc)) return null; + return desc; +} + +interface ParamTagInfo { + description: string | null; + typeOverride: string | null; +} + +function readParamTags(jsdoc: JSDoc | null): Map { + const map = new Map(); + if (!jsdoc) return map; + for (const tag of jsdoc.getTags()) { + if (tag.getTagName() !== 'param') continue; + const paramTag = tag as JSDocParameterTag; + const nameNode = paramTag.getNameNode(); + if (!nameNode) continue; + const name = nameNode.getText(); + const raw = sanitizeJsDocText(stripTsDocDash(paramTag.getCommentText() ?? '')); + map.set(name, splitLeadingLink(raw)); + } + return map; +} + +/** + * If the text starts with a `{@link X}` marker (planted by sanitizeJsDocText), + * extracts X as a type-override and returns the rest as the description. + */ +function splitLeadingLink(text: string): ParamTagInfo { + if (text.startsWith(LINK_MARKER_OPEN)) { + const end = text.indexOf(LINK_MARKER_CLOSE, LINK_MARKER_OPEN.length); + if (end !== -1) { + const target = text.slice(LINK_MARKER_OPEN.length, end).trim(); + const remaining = text.slice(end + LINK_MARKER_CLOSE.length).trim(); + return { typeOverride: target, description: remaining || null }; + } + } + return { typeOverride: null, description: text || null }; +} + +/** TSDoc writes `@param name - description`; strip the leading dash. */ +function stripTsDocDash(text: string): string { + return text.replace(/^\s*[-–—]\s*/, ''); +} + +function readExamples(jsdoc: JSDoc | null): string[] { + if (!jsdoc) return []; + const out: string[] = []; + for (const tag of jsdoc.getTags()) { + if (tag.getTagName() !== 'example') continue; + const text = tag.getCommentText()?.trim(); + if (text) out.push(text); + } + return out; +} + +function readExpandNames(jsdoc: JSDoc | null): Set { + const out = new Set(); + if (!jsdoc) return out; + for (const tag of jsdoc.getTags()) { + if (tag.getTagName() !== 'expand') continue; + const text = tag.getCommentText()?.trim(); + if (text) out.add(text); + } + return out; +} + +function readSamples(jsdoc: JSDoc | null): string[] { + if (!jsdoc) return []; + const out: string[] = []; + for (const tag of jsdoc.getTags()) { + if (tag.getTagName() !== 'sample') continue; + const text = tag.getCommentText()?.trim(); + if (!text) continue; + if (!text.includes('#')) { + throw new Error(`Invalid @sample value: "${text}". Expected format \`dir/path#SAMPLE_NAME\`.`); + } + out.push(text); + } + return out; +} + +function readReturnInfo(jsdoc: JSDoc | null): ParamTagInfo { + const empty: ParamTagInfo = { description: null, typeOverride: null }; + if (!jsdoc) return empty; + for (const tag of jsdoc.getTags()) { + const tagName = tag.getTagName(); + if (tagName !== 'returns' && tagName !== 'return') continue; + const raw = sanitizeJsDocText(stripTsDocDash(tag.getCommentText() ?? '')); + return splitLeadingLink(raw); + } + return empty; +} + +function readPropertyJsDoc(node: Node): string | null { + if (!Node.isJSDocable(node)) return null; + const docs = node.getJsDocs(); + if (docs.length === 0) return null; + const desc = sanitizeJsDocText(docs[docs.length - 1].getDescription()); + return desc || null; +} + +export const LINK_MARKER_OPEN = 'LINK:'; +export const LINK_MARKER_CLOSE = ''; + +/** + * Replaces JSDoc inline tags with sanitized text. {@link Foo} survives as a + * sentinel marker (LINK_MARKER_OPEN…LINK_MARKER_CLOSE) so the renderer can + * later turn it into a markdown link if `Foo` is itself documented in the + * same reference. Other inline tags ({@linkcode}, {@see}, …) collapse to + * their target/label text. Loose `{`/`}` are escaped so MDX doesn't treat + * them as JS expressions. + */ +function sanitizeJsDocText(text: string): string { + let result = text.replace( + /\{@link\s+([^}|]+?)(?:\s*\|\s*[^}]*)?\}/g, + (_, target: string) => `${LINK_MARKER_OPEN}${target.trim()}${LINK_MARKER_CLOSE}`, + ); + result = result.replace( + /\{@(linkcode|linkplain|inheritDoc|see|tutorial|label)\s+([^}]*)\}/g, + (_, _tag: string, body: string) => { + const trimmed = body.trim(); + const pipeIdx = trimmed.indexOf('|'); + if (pipeIdx >= 0) return trimmed.slice(pipeIdx + 1).trim(); + return trimmed; + }, + ); + return result.replace(/[{}]/g, (m) => `\\${m}`).trim(); +} diff --git a/docs/reference-generator/src/index.ts b/docs/reference-generator/src/index.ts new file mode 100644 index 000000000..fc5512c56 --- /dev/null +++ b/docs/reference-generator/src/index.ts @@ -0,0 +1,114 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { mkdirSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { collectPublicApi } from './collect'; +import { extract } from './extract'; +import type { Extracted } from './extract'; +import { render } from './render'; +import type { PackageKey } from './render'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const REPO_ROOT = resolve(HERE, '../../..'); + +const PACKAGES: Record = { + appkit: 'packages/appkit', + 'appkit-react': 'packages/appkit-react', +}; + +/** + * URL prefixes used to point cross-package `{@link X}` references at sibling + * reference pages in the published docs. Keyed by `PackageKey`; appended + * before `#anchor` when a symbol resolves to a different package. + */ +const PUBLISHED_URL: Record = { + appkit: '/ecosystem/appkit/reference/appkit', + 'appkit-react': '/ecosystem/appkit/reference/appkit-react', +}; + +function parseTargets(argv: string[]): PackageKey[] { + const flag = argv.find((a) => a.startsWith('--package=')); + const value = flag?.split('=')[1] ?? 'all'; + if (value === 'all') return ['appkit', 'appkit-react']; + if (value === 'appkit' || value === 'appkit-react') return [value]; + throw new Error(`Unknown --package value: ${value}`); +} + +function collectForPackage(pkg: PackageKey): Extracted[] { + const packagePath = join(REPO_ROOT, PACKAGES[pkg]); + const collected = collectPublicApi({ packagePath }); + const extracted: Extracted[] = collected.map(extract); + + const missing = extracted + .map((e) => { + const tags: string[] = []; + if (!e.category) tags.push('@category'); + if (!e.section) tags.push('@section'); + return tags.length > 0 ? { name: e.name, sourcePath: e.sourcePath, tags } : null; + }) + .filter((m): m is { name: string; sourcePath: string; tags: string[] } => m !== null); + + if (missing.length > 0) { + const list = missing.map((m) => ` - ${m.name} (${m.sourcePath}) — missing ${m.tags.join(', ')}`).join('\n'); + throw new Error( + `[${pkg}] ${missing.length} public export(s) missing required JSDoc tags:\n${list}\n\n` + + `Every @public symbol must declare both @category (top-level group, e.g. \`@category Action\`) and @section (sub-group, e.g. \`@section Balances\`).`, + ); + } + + return extracted; +} + +function main(): void { + const targets = parseTargets(process.argv.slice(2)); + + // Collect both packages first so each render pass knows which symbols live + // in the sibling document and can emit absolute URLs instead of dead local + // anchors for cross-package `{@link X}` references. + const collected: Record = { + appkit: collectForPackage('appkit'), + 'appkit-react': collectForPackage('appkit-react'), + }; + + for (const pkg of targets) { + const externalRefs = new Map(); + for (const otherPkg of Object.keys(collected) as PackageKey[]) { + if (otherPkg === pkg) continue; + for (const entry of collected[otherPkg]) { + externalRefs.set(entry.name, PUBLISHED_URL[otherPkg]); + } + } + + // Package prefixes for the explicit `{@link pkg:Name}` form. The + // current package maps to an empty prefix so authors can write + // qualified links from within their own package and still get local + // anchors instead of fully-qualified URLs. + const packagePrefixes = new Map(); + for (const otherPkg of Object.keys(collected) as PackageKey[]) { + packagePrefixes.set(otherPkg, otherPkg === pkg ? '' : PUBLISHED_URL[otherPkg]); + } + + const output = render(collected[pkg], { externalRefs, packagePrefixes }); + const entryCount = collected[pkg].length; + + const outPath = join(REPO_ROOT, 'docs/templates/packages', pkg, 'docs/reference.md'); + const target = `packages/${pkg}/docs/reference.md`; + const frontMatter = `---\ntarget: ${target}\n---\n\n`; + + mkdirSync(dirname(outPath), { recursive: true }); + writeFileSync(outPath, frontMatter + output); + + const relativePath = outPath.slice(REPO_ROOT.length + 1); + console.log(`✓ ${relativePath} (${entryCount} entries) → target ${target}`); + } +} + +main(); diff --git a/docs/reference-generator/src/render.ts b/docs/reference-generator/src/render.ts new file mode 100644 index 000000000..f2d558c05 --- /dev/null +++ b/docs/reference-generator/src/render.ts @@ -0,0 +1,463 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +import { LINK_MARKER_CLOSE, LINK_MARKER_OPEN } from './extract'; +import type { + Extracted, + ExtractedClass, + ExtractedComponent, + ExtractedFunction, + ExtractedNamespaceComponent, + ExtractedType, + ParamRow, +} from './extract'; + +export type PackageKey = 'appkit' | 'appkit-react'; + +const TODO_MARKER = '_TODO: describe_'; + +const CATEGORY_ORDER = ['Action', 'Hook', 'Component', 'Class', 'Type', 'Constants']; + +/** + * Symbol-name → URL-prefix map used to resolve unqualified `{@link X}` + * references and type-cell auto-links. Empty string means "local to this + * document" (the link resolves to `#anchor`); a non-empty prefix is + * prepended before `#anchor` so the reference points to a sibling reference + * page in the published docs. + */ +let LINKABLE: Map = new Map(); + +/** + * Package-prefix → URL map used to resolve qualified `{@link pkg:Name}` + * references. The current package is included with an empty prefix so authors + * can write `{@link appkit-react:Foo}` from inside appkit-react and still get + * a local anchor. + */ +let PACKAGE_PREFIX: Map = new Map(); + +export interface RenderOptions { + /** Symbols documented in other packages, keyed by name with their URL prefix as value. */ + externalRefs?: Map; + /** Map of package-key → URL prefix (current package's value should be `""`). Enables `{@link pkg:Name}` syntax. */ + packagePrefixes?: Map; +} + +export function render(extracted: Extracted[], options: RenderOptions = {}): string { + const externalRefs = options.externalRefs ?? new Map(); + PACKAGE_PREFIX = options.packagePrefixes ?? new Map(); + + LINKABLE = new Map(); + for (const [name, prefix] of externalRefs) LINKABLE.set(name, prefix); + // Local entries override any external mapping with the same name. + for (const e of extracted) LINKABLE.set(e.name, ''); + + const parts: string[] = []; + + const byCategory = groupByCategory(extracted); + const categories = sortCategories([...byCategory.keys()]); + + for (const category of categories) { + const entries = byCategory.get(category)!; + appendCategoryBlock(parts, category, entries); + } + + return ( + parts + .join('\n') + .replace(/\n{3,}/g, '\n\n') + .trimEnd() + '\n' + ); +} + +function groupByCategory(extracted: Extracted[]): Map { + const grouped = new Map(); + for (const item of extracted) { + const list = grouped.get(item.category) ?? []; + list.push(item); + grouped.set(item.category, list); + } + return grouped; +} + +function sortCategories(categories: string[]): string[] { + const known = CATEGORY_ORDER.filter((t) => categories.includes(t)); + const others = categories.filter((t) => !CATEGORY_ORDER.includes(t)).sort(); + return [...known, ...others]; +} + +function appendCategoryBlock(parts: string[], category: string, entries: Extracted[]): void { + parts.push(`## ${category}`); + parts.push(''); + + const grouped = new Map(); + for (const item of entries) { + const list = grouped.get(item.section) ?? []; + list.push(item); + grouped.set(item.section, list); + } + for (const list of grouped.values()) { + list.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + } + + const orderedSections = [...grouped.keys()].sort(); + + for (const sectionTitle of orderedSections) { + const sectionEntries = grouped.get(sectionTitle)!; + parts.push(`### ${sectionTitle}`); + parts.push(''); + for (const entry of sectionEntries) { + parts.push(renderEntry(entry, '####')); + parts.push(''); + } + } +} + +type HeadingLevel = '###' | '####'; + +function renderEntry(entry: Extracted, level: HeadingLevel): string { + switch (entry.kind) { + case 'function': + return renderFunction(entry, level); + case 'component': + return renderComponent(entry, level); + case 'componentNamespace': + return renderNamespaceComponent(entry, level); + case 'type': + return renderType(entry, level); + case 'class': + return renderClass(entry, level); + } +} + +function renderFunction(entry: ExtractedFunction, level: HeadingLevel): string { + const lines: string[] = []; + lines.push(`${level} ${entry.name}`); + lines.push(''); + lines.push(resolveLinks(entry.summary ?? TODO_MARKER)); + lines.push(''); + if (entry.params.length > 0) { + lines.push(renderParamsTable(entry.params)); + lines.push(''); + } + const returnType = entry.returnTypeOverride + ? formatTypeOverride(entry.returnTypeOverride) + : formatTypeCell(entry.returnTypeText); + if (entry.returnDescription) { + const desc = resolveLinks(entry.returnDescription).replace(/\r?\n/g, ' '); + lines.push(`Returns: ${returnType} — ${desc}`); + } else { + lines.push(`Returns: ${returnType}.`); + } + appendExamples(lines, entry.examples, entry.samples); + return lines.join('\n'); +} + +function renderComponent(entry: ExtractedComponent, level: HeadingLevel): string { + const lines: string[] = []; + lines.push(`${level} ${entry.name}`); + lines.push(''); + lines.push(resolveLinks(entry.summary ?? TODO_MARKER)); + lines.push(''); + if (entry.props.length > 0) { + lines.push(renderPropsTable(entry.props)); + } + appendExamples(lines, entry.examples, entry.samples); + return lines.join('\n'); +} + +function renderNamespaceComponent(entry: ExtractedNamespaceComponent, level: HeadingLevel): string { + const lines: string[] = []; + lines.push(`${level} ${entry.name}`); + lines.push(''); + lines.push(resolveLinks(entry.summary ?? TODO_MARKER)); + lines.push(''); + + if (entry.members.length === 0) { + appendExamples(lines, entry.examples, entry.samples); + return lines.join('\n').trimEnd(); + } + + // When any member declares its own props, fall back to per-member sub-headings + // so the props table can sit under the member it documents. + const anyWithProps = entry.members.some((m) => m.props.length > 0); + if (anyWithProps) { + const memberLevel = level === '###' ? '####' : '#####'; + lines.push('**Members**'); + lines.push(''); + for (const member of entry.members) { + lines.push(`${memberLevel} ${entry.name}.${member.name}`); + lines.push(''); + lines.push(resolveLinks(member.summary ?? TODO_MARKER)); + lines.push(''); + if (member.props.length > 0) { + lines.push(renderPropsTable(member.props)); + lines.push(''); + } + } + appendExamples(lines, entry.examples, entry.samples); + return lines.join('\n').trimEnd(); + } + + // Compact members table — readable and scannable for sub-components without props. + lines.push('**Members**'); + lines.push(''); + lines.push('| Member | Description |'); + lines.push('| --- | --- |'); + for (const member of entry.members) { + const name = `\`${entry.name}.${member.name}\``; + const desc = resolveLinks(member.summary ?? TODO_MARKER) + .replace(/\r?\n+/g, ' ') + .replace(/\|/g, '\\|'); + lines.push(`| ${name} | ${desc} |`); + } + lines.push(''); + appendExamples(lines, entry.examples, entry.samples); + return lines.join('\n').trimEnd(); +} + +function renderType(entry: ExtractedType, level: HeadingLevel): string { + const lines: string[] = []; + lines.push(`${level} ${entry.name}`); + lines.push(''); + lines.push(resolveLinks(entry.summary ?? TODO_MARKER)); + lines.push(''); + if (entry.fields && entry.fields.length > 0) { + lines.push(renderFieldsTable(entry.fields)); + } else if (entry.typeText) { + lines.push('```ts'); + const keyword = entry.isConstant ? 'const' : 'type'; + const operator = entry.isConstant ? '=' : '='; + lines.push(`${keyword} ${entry.name} ${operator} ${entry.typeText};`); + lines.push('```'); + } else { + lines.push('_Empty type._'); + } + return lines.join('\n'); +} + +function renderClass(entry: ExtractedClass, level: HeadingLevel): string { + const lines: string[] = []; + lines.push(`${level} ${entry.name}`); + lines.push(''); + lines.push(resolveLinks(entry.summary ?? TODO_MARKER)); + lines.push(''); + if (entry.constructorParams && entry.constructorParams.length > 0) { + const topLevelNames = entry.constructorParams.filter((p) => !p.name.includes('.')).map((p) => p.name); + lines.push(`Constructor: \`new ${entry.name}(${topLevelNames.join(', ')})\``); + lines.push(''); + lines.push(renderParamsTable(entry.constructorParams)); + } else { + lines.push(`Constructor: \`new ${entry.name}()\``); + } + appendExamples(lines, entry.examples, entry.samples); + return lines.join('\n'); +} + +function appendExamples(lines: string[], examples: string[], samples: string[]): void { + const total = examples.length + samples.length; + if (total === 0) return; + lines.push(''); + lines.push(total > 1 ? '**Examples**' : '**Example**'); + lines.push(''); + for (const example of examples) { + lines.push(example); + lines.push(''); + } + for (const sample of samples) { + lines.push(`%%${sample}%%`); + lines.push(''); + } +} + +function renderParamsTable(rows: ParamRow[]): string { + return renderRowsTable('Parameter', rows); +} + +function renderPropsTable(rows: ParamRow[]): string { + return renderRowsTable('Prop', rows); +} + +function renderFieldsTable(rows: ParamRow[]): string { + return renderRowsTable('Field', rows); +} + +function renderRowsTable(firstHeader: string, rows: ParamRow[]): string { + const headers = [firstHeader, 'Type', 'Description']; + return renderTable( + headers, + rows.map((r) => [ + `\`${r.name}\`${r.required ? '\\*' : ''}`, + r.typeOverride ? formatTypeOverride(r.typeOverride) : formatTypeCell(r.typeText), + resolveLinks(r.description ?? TODO_MARKER), + ]), + ); +} + +function renderTable(headers: string[], rows: string[][]): string { + const lines: string[] = []; + lines.push(`| ${headers.join(' | ')} |`); + lines.push(`| ${headers.map(() => '---').join(' | ')} |`); + for (const row of rows) { + lines.push(`| ${row.map((cell) => cell.replace(/\r?\n/g, ' ')).join(' | ')} |`); + } + return lines.join('\n'); +} + +function escapeForCell(text: string): string { + return text.replace(/\|/g, '\\|'); +} + +/** + * Renders a type cell as a single `` chip with linked names inlined as + * `` children. The wrapping `` keeps Mintlify's chip styling unified + * across the whole compound type (e.g., `ConnectorInput[]` stays one chip + * instead of fragmenting into a chip-link + plain chip combo), while the + * inline `` preserves the precise link scope on the symbol name only. + */ +function formatTypeCell(typeText: string): string { + if (LINKABLE.size === 0) return '`' + escapeForCell(typeText) + '`'; + + const names = [...LINKABLE.keys()].sort((a, b) => b.length - a.length); + const pattern = new RegExp(`\\b(${names.map(escapeRegex).join('|')})\\b`, 'g'); + + let body = ''; + let lastIndex = 0; + let match: RegExpExecArray | null; + let matched = false; + while ((match = pattern.exec(typeText)) !== null) { + matched = true; + if (match.index > lastIndex) { + body += escapeHtmlInCell(typeText.slice(lastIndex, match.index)); + } + const prefix = LINKABLE.get(match[1]) ?? ''; + body += `${match[1]}`; + lastIndex = pattern.lastIndex; + } + if (!matched) return '`' + escapeForCell(typeText) + '`'; + if (lastIndex < typeText.length) { + body += escapeHtmlInCell(typeText.slice(lastIndex)); + } + return `${body}`; +} + +function escapeHtmlInCell(text: string): string { + // `{`/`}` need entity escapes because Mintlify's MDX parser treats them as + // JSX-expression delimiters even inside `` blocks. + return text + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/\{/g, '{') + .replace(/\}/g, '}') + .replace(/\|/g, '\\|'); +} + +function escapeRegex(str: string): string { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +/** + * Renders a type-override that the author requested via `{@link X}` (or + * `{@link pkg:X}`) at the start of a `@param` or `@returns` description. + * Qualified forms point at the matching sibling reference; unqualified forms + * use the LINKABLE lookup. Unknown package prefixes throw — same contract as + * `resolveLinks` — so authors can't accidentally ship a dead chip. + */ +function formatTypeOverride(raw: string): string { + const colon = raw.indexOf(':'); + if (colon > 0) { + const pkg = raw.slice(0, colon).trim(); + const name = raw.slice(colon + 1).trim(); + if (!PACKAGE_PREFIX.has(pkg)) { + const known = [...PACKAGE_PREFIX.keys()].join(', '); + throw new Error(`Unknown package prefix in {@link ${raw}}. Got "${pkg}"; expected one of: ${known}.`); + } + const prefix = PACKAGE_PREFIX.get(pkg) ?? ''; + return `[\`${name}\`](${prefix}#${slugify(name)})`; + } + if (LINKABLE.has(raw)) { + const prefix = LINKABLE.get(raw) ?? ''; + return `[\`${raw}\`](${prefix}#${slugify(raw)})`; + } + return '`' + raw + '`'; +} + +function slugify(name: string): string { + return name.toLowerCase(); +} + +/** + * Resolves `{@link Foo}` markers (planted by sanitizeJsDocText) into markdown + * links. Two forms are recognized: + * + * - **Qualified** `{@link pkg:Name}` — the prefix names a sibling package + * from `PACKAGE_PREFIX`; the link gets that package's URL prefix. Unknown + * package prefixes fall through to the unqualified path (treats the colon + * as part of the symbol name and emits a dead local anchor). + * - **Unqualified** `{@link Foo}` — looked up in `LINKABLE`: local names + * resolve to `#anchor`, cross-package names get the sibling reference's + * URL prefix, anything else emits a dead local anchor. + * + * In both cases the displayed text is the bare symbol name (without the + * package prefix), so qualified and unqualified forms render identically. + */ +function resolveLinks(text: string): string { + if (!text.includes(LINK_MARKER_OPEN)) return text; + const out: string[] = []; + let cursor = 0; + while (cursor < text.length) { + const start = text.indexOf(LINK_MARKER_OPEN, cursor); + if (start === -1) { + out.push(text.slice(cursor)); + break; + } + out.push(text.slice(cursor, start)); + const end = text.indexOf(LINK_MARKER_CLOSE, start + LINK_MARKER_OPEN.length); + if (end === -1) { + out.push(text.slice(start)); + break; + } + const raw = text.slice(start + LINK_MARKER_OPEN.length, end).trim(); + + const colon = raw.indexOf(':'); + if (colon > 0) { + const pkg = raw.slice(0, colon).trim(); + const name = raw.slice(colon + 1).trim(); + if (!PACKAGE_PREFIX.has(pkg)) { + const known = [...PACKAGE_PREFIX.keys()].join(', '); + throw new Error(`Unknown package prefix in {@link ${raw}}. Got "${pkg}"; expected one of: ${known}.`); + } + const prefix = PACKAGE_PREFIX.get(pkg) ?? ''; + out.push(renderUnqualifiedLink(name, prefix)); + } else { + const prefix = LINKABLE.get(raw) ?? ''; + out.push(renderUnqualifiedLink(raw, prefix)); + } + cursor = end + LINK_MARKER_CLOSE.length; + } + return out.join(''); +} + +/** + * Renders a `{@link Name}` (or its already-resolved cross-package counterpart) + * to a markdown link. Dot-form references like `Foo.Bar` resolve to the parent + * symbol's anchor (`#foo`) when `Foo` is itself documented — compound members + * don't get their own anchors, so this keeps the chip linkable to the parent's + * section where the member is listed. + */ +function renderUnqualifiedLink(name: string, prefix: string): string { + const dot = name.indexOf('.'); + if (dot > 0) { + const parent = name.slice(0, dot); + if (LINKABLE.has(parent)) { + const parentPrefix = prefix || LINKABLE.get(parent) || ''; + return `[\`${name}\`](${parentPrefix}#${slugify(parent)})`; + } + } + return `[\`${name}\`](${prefix}#${slugify(name)})`; +} diff --git a/docs/reference-generator/tsconfig.json b/docs/reference-generator/tsconfig.json new file mode 100644 index 000000000..67fb71213 --- /dev/null +++ b/docs/reference-generator/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "Bundler", + "target": "ES2022", + "strict": true, + "noImplicitAny": true, + "skipLibCheck": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "noEmit": true + }, + "include": ["src/**/*"] +} diff --git a/docs/template-resolver/package.json b/docs/template-resolver/package.json new file mode 100644 index 000000000..9679068f3 --- /dev/null +++ b/docs/template-resolver/package.json @@ -0,0 +1,19 @@ +{ + "name": "@ton/template-resolver", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "Resolves %%dir/path#SAMPLE_NAME%% placeholders in docs/templates/**/*.md by injecting code from SAMPLE_START/SAMPLE_END blocks in the source tree.", + "scripts": { + "resolve": "tsx src/index.ts", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "eslint": "^9.39.4", + "prettier": "^3.6.2" + }, + "devDependencies": { + "tsx": "^4.21.0", + "typescript": "~5.9.3" + } +} diff --git a/scripts/extract-samples.ts b/docs/template-resolver/src/extract-samples.ts similarity index 100% rename from scripts/extract-samples.ts rename to docs/template-resolver/src/extract-samples.ts diff --git a/scripts/update-docs.ts b/docs/template-resolver/src/index.ts similarity index 90% rename from scripts/update-docs.ts rename to docs/template-resolver/src/index.ts index ce49f84f8..706405fcd 100644 --- a/scripts/update-docs.ts +++ b/docs/template-resolver/src/index.ts @@ -8,12 +8,18 @@ import fs from 'fs/promises'; import path from 'path'; +import { dirname, resolve } from 'path'; +import { fileURLToPath } from 'url'; import { ESLint } from 'eslint'; import * as prettier from 'prettier'; import { extractSamplesFromFile } from './extract-samples'; +const HERE = dirname(fileURLToPath(import.meta.url)); +const REPO_ROOT = resolve(HERE, '../../..'); +const TEMPLATES_DIR_NAME = 'docs/templates'; + type Placeholder = { raw: string; body: string; @@ -35,7 +41,6 @@ function validateDirPath(dirPath: string): void { } function isJSXCode(code: string): boolean { - // Check if code contains JSX syntax (tags like
      , , etc.) const jsxPattern = /<[A-Za-z][A-Za-z0-9]*(\s|>)/; return jsxPattern.test(code); } @@ -50,16 +55,16 @@ async function formatSampleCode(sample: string, filePath?: string): Promise { - const templateDir = path.resolve('template'); + const templateDir = path.resolve(REPO_ROOT, TEMPLATES_DIR_NAME); try { const stat = await fs.stat(templateDir); if (!stat.isDirectory()) { @@ -223,7 +228,6 @@ async function resolvePlaceholder( } } - // SAMPLE_NAME_1, SAMPLE_NAME_2, ..., SAMPLE_NAME_N let sample = allSamples.get(placeholder.sampleName); if (!sample) { @@ -237,7 +241,6 @@ async function resolvePlaceholder( if (!isNaN(index)) { parts.push({ name, code, index }); if (!sourceFilePath) { - // Find the file that contains this sample for (const file of files) { const fileSamples = sampleCache.get(file); if (fileSamples?.has(name)) { @@ -259,7 +262,6 @@ async function resolvePlaceholder( parts.sort((a, b) => a.index - b.index); sample = parts.map((p) => p.code).join('\n\n'); } else { - // Find the file that contains this sample for (const file of files) { const fileSamples = sampleCache.get(file); if (fileSamples?.has(placeholder.sampleName)) { @@ -277,7 +279,6 @@ async function resolvePlaceholder( } async function processTemplateFile(templatePath: string): Promise { - const cwd = process.cwd(); const templateContent = await fs.readFile(templatePath, 'utf8'); const { params, body: templateBody } = parseTemplateParams(templateContent); @@ -286,16 +287,14 @@ async function processTemplateFile(templatePath: string): Promise { const sampleCache = new Map>(); - // Replace placeholders let result = templateBody; for (const placeholder of placeholders) { - const injected = await resolvePlaceholder(cwd, placeholder, sampleCache); + const injected = await resolvePlaceholder(REPO_ROOT, placeholder, sampleCache); result = result.replace(placeholder.raw, injected); } - // Use target from template parameters - const outPath = path.resolve(cwd, params.target); - const sourceRelative = path.relative(cwd, templatePath); + const outPath = path.resolve(REPO_ROOT, params.target); + const sourceRelative = path.relative(REPO_ROOT, templatePath); const generatedHeader = ` # @ton/appkit-react @@ -148,7 +148,7 @@ export const Balance = () => { return
      Loading...
      ; } - return
      Balance: {balance?.toString()} TON
      ; + return
      Balance: {balance || 0} TON
      ; }; ``` diff --git a/packages/appkit-react/docs/components.md b/packages/appkit-react/docs/components.md index d63760fbf..2351dc37c 100644 --- a/packages/appkit-react/docs/components.md +++ b/packages/appkit-react/docs/components.md @@ -1,7 +1,7 @@ # Components @@ -17,8 +17,8 @@ Source template: template/packages/appkit-react/docs/components.md ```tsx return ( +

      My App

      {/* Your App Content */} -
      My App
      ); ``` diff --git a/packages/appkit-react/docs/creating-swap-provider.md b/packages/appkit-react/docs/creating-swap-provider.md index 57969e6fd..e09980976 100644 --- a/packages/appkit-react/docs/creating-swap-provider.md +++ b/packages/appkit-react/docs/creating-swap-provider.md @@ -118,4 +118,4 @@ const appKit = new AppKit({ }); ``` -Multiple providers can be registered. AppKit uses the first provider by default; pass `providerId` to hooks to target a specific one. +Multiple providers can be registered. AppKit uses the first provider by default. Pass `providerId` to hooks to target a specific one. diff --git a/packages/appkit-react/docs/hooks.md b/packages/appkit-react/docs/hooks.md index dbce1b294..bdec20e9a 100644 --- a/packages/appkit-react/docs/hooks.md +++ b/packages/appkit-react/docs/hooks.md @@ -1,7 +1,7 @@ # Hooks @@ -51,7 +51,7 @@ if (error) { return
      Error: {error.message}
      ; } -return
      Balance: {balance?.toString()}
      ; +return
      Balance: {balance}
      ; ``` ### `useBalanceByAddress` @@ -75,7 +75,7 @@ if (error) { return
      Error: {error.message}
      ; } -return
      Balance: {balance?.toString()}
      ; +return
      Balance: {balance}
      ; ``` ### `useWatchBalance` @@ -248,7 +248,7 @@ if (error) { return
      Error: {error.message}
      ; } -return
      Jetton Wallet Address: {walletAddress?.toString()}
      ; +return
      Jetton Wallet Address: {walletAddress}
      ; ``` ### `useTransferJetton` @@ -413,7 +413,7 @@ return (

      NFT Details

      Name: {nft?.info?.name}

      Collection: {nft?.collection?.name}

      -

      Owner: {nft?.ownerAddress?.toString()}

      +

      Owner: {nft?.ownerAddress}

      ); ``` @@ -444,7 +444,7 @@ return (

      My NFTs

        {nfts?.nfts.map((nft) => ( -
      • +
      • {nft.info?.name} ({nft.collection?.name})
      • ))} @@ -480,7 +480,7 @@ return (

        NFTs

          {nfts?.nfts.map((nft) => ( -
        • +
        • {nft.info?.name} ({nft.collection?.name})
        • ))} @@ -1063,7 +1063,7 @@ return (
            {connectedWallets.map((wallet) => (
          • - {wallet.getAddress()} ({wallet.getNetwork().toString()}) + {wallet.getAddress()} ({wallet.getNetwork().chainId})
          • ))}
          diff --git a/packages/appkit-react/docs/reference.md b/packages/appkit-react/docs/reference.md new file mode 100644 index 000000000..416a2708b --- /dev/null +++ b/packages/appkit-react/docs/reference.md @@ -0,0 +1,4046 @@ + + +## Hook + +### Balances + +#### useBalance + +React hook reading the Toncoin balance of the currently selected wallet through TanStack Query — auto-resolves the wallet address (use [`useBalanceByAddress`](#usebalancebyaddress) for an arbitrary address). + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseBalanceParameters`](#usebalanceparameters) | TanStack Query overrides (`select`, `enabled`, `staleTime`, …) and an optional network override. | +| `parameters.address` | UserFriendlyAddress \| Address | Wallet address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `parameters.network` | Network | Network to read the balance from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseBalanceReturnType<selectData = GetBalanceByAddressData> — TanStack Query result for the balance read. + +**Example** + +```tsx +const { data: balance, isLoading, error } = useBalance(); + +if (isLoading) { + return
          Loading...
          ; +} + +if (error) { + return
          Error: {error.message}
          ; +} + +return
          Balance: {balance}
          ; +``` + +#### useBalanceByAddress + +React hook reading the Toncoin balance of an arbitrary address through TanStack Query — useful for addresses that aren't tied to the selected wallet (use [`useBalance`](#usebalance) for the selected wallet). + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseBalanceByAddressParameters`](#usebalancebyaddressparameters) | Target address, optional network override, and TanStack Query overrides. | +| `parameters.address` | UserFriendlyAddress \| Address | Wallet address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `parameters.network` | Network | Network to read the balance from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseBalanceByAddressReturnType<selectData = GetBalanceByAddressData> — TanStack Query result for the balance read. + +**Example** + +```tsx +const { + data: balance, + isLoading, + error, +} = useBalanceByAddress({ + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', +}); + +if (isLoading) { + return
          Loading...
          ; +} + +if (error) { + return
          Error: {error.message}
          ; +} + +return
          Balance: {balance}
          ; +``` + +#### useWatchBalance + +Subscribe to Toncoin balance updates for the currently selected wallet. Updates flow into the TanStack Query cache so [`useBalance`](#usebalance) picks up the new data automatically (use [`useWatchBalanceByAddress`](#usewatchbalancebyaddress) for a fixed address). Requires a streaming provider registered for the network — the hook exits silently with a console warning when none is configured. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseWatchBalanceParameters`](#usewatchbalanceparameters) | Update callback and optional network override. | +| `parameters.onChange` | (update: BalanceUpdate) => void | Callback fired on every balance update from the streaming provider. | +| `parameters.network` | Network | Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +Returns: `void`. + +**Example** + +```tsx +const { data: balance } = useBalance(); + +useWatchBalance(); + +return
          Current balance: {balance}
          ; +``` + +#### useWatchBalanceByAddress + +Subscribe to Toncoin balance updates for an arbitrary address — updates flow into the TanStack Query cache so [`useBalanceByAddress`](#usebalancebyaddress) picks up the new data automatically. Requires a streaming provider registered for the network — the hook exits silently with a console warning when none is configured. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters`\* | [`UseWatchBalanceByAddressParameters`](#usewatchbalancebyaddressparameters) | Address, update callback and optional network override. | +| `parameters.address` | UserFriendlyAddress \| Address | Wallet address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `parameters.network` | Network | Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.onChange` | (update: BalanceUpdate) => void | Callback fired on every balance update from the streaming provider. | + +Returns: `void`. + +**Example** + +```tsx +const address = 'UQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJKZ'; +const network = Network.mainnet(); +const { data: balance } = useBalanceByAddress({ address, network }); + +useWatchBalanceByAddress({ address, network }); + +return
          Current balance: {balance}
          ; +``` + +### Connectors + +#### useConnectorById + +Look up a connector by its id and stay subscribed to its registration lifecycle — updates when a connector with that id is registered (via AppKit's constructor or [`addConnector`](/ecosystem/appkit/reference/appkit#addconnector)) or unregistered. Returns the matching [`Connector`](/ecosystem/appkit/reference/appkit#connector), or `undefined` when none with that id is currently registered. Use [`useConnectedWallets`](#useconnectedwallets) if you want to react to wallet connect/disconnect events instead. + +| Parameter | Type | Description | +| --- | --- | --- | +| `id`\* | `string` | ID of the connector to look up. | + +Returns: Connector \| undefined — The matching [`Connector`](/ecosystem/appkit/reference/appkit#connector), or `undefined` if none with that id is registered. + +#### useConnectors + +Read the list of connectors registered on this AppKit instance. Updates when a connector is registered or unregistered (use [`useConnectedWallets`](#useconnectedwallets) to react to wallet connect/disconnect events). + +Returns: UseConnectorsReturnType — Read-only array of registered [`Connector`](/ecosystem/appkit/reference/appkit#connector)s. + +### Crypto Onramp + +#### useCreateCryptoOnrampDeposit + +Create a crypto-onramp deposit from a quote previously obtained via [`useCryptoOnrampQuote`](#usecryptoonrampquote). Call `mutate(options)` where `options` matches [`CreateCryptoOnrampDepositOptions`](/ecosystem/appkit/reference/appkit#createcryptoonrampdepositoptions) (quote, refund address, optional provider override). On success, `data` is the [`CryptoOnrampDeposit`](/ecosystem/appkit/reference/appkit#cryptoonrampdeposit) carrying the address and amount the user must send on the source chain to complete the onramp. Pair with [`useCryptoOnrampStatus`](#usecryptoonrampstatus) to poll the deposit until it settles. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseCreateCryptoOnrampDepositParameters`](#usecreatecryptoonrampdepositparameters) | TanStack Query mutation overrides (`parameters.mutation`). | +| `parameters.mutation` | [`MutationOptionsOverride`](/ecosystem/appkit/reference/appkit#mutationoptionsoverride) | TanStack Query mutation options forwarded to `useMutation` (`onSuccess`, `onError`, `onMutate`, `retry`, …). `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper. | + +Returns: UseCreateCryptoOnrampDepositReturnType<context = unknown> — Mutation result for the deposit call. + +#### useCryptoOnrampContext + +Reads the `CryptoOnrampContext` populated by [`CryptoOnrampWidgetProvider`](#cryptoonrampwidgetprovider) — returns the widget's selection state, quote/deposit data and actions ([`CryptoOnrampContextType`](#cryptoonrampcontexttype)). + +Returns: CryptoOnrampContextType. + +#### useCryptoOnrampProvider + +Read a registered crypto-onramp provider by id, or the default provider when no id is given — subscribes to [`watchCryptoOnrampProviders`](/ecosystem/appkit/reference/appkit#watchcryptoonrampproviders) and re-reads via [`getCryptoOnrampProvider`](/ecosystem/appkit/reference/appkit#getcryptoonrampprovider) so the result stays in sync. The read swallows the throw from [`getCryptoOnrampProvider`](/ecosystem/appkit/reference/appkit#getcryptoonrampprovider) (which throws when no provider matches — or when no id is passed and no default has been registered) and yields `undefined` instead. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseCryptoOnrampProviderParameters`](#usecryptoonrampproviderparameters) | Optional provider id. | +| `parameters.id` | `string` | Provider ID to look up. When omitted, returns the registered default provider. | + +Returns: UseCryptoOnrampProviderReturnType — The matching provider, or `undefined` when none is registered. + +#### useCryptoOnrampProviders + +List every crypto-onramp provider registered on the AppKit instance (both those passed via [`AppKitConfig`](/ecosystem/appkit/reference/appkit#appkitconfig)'s `providers` and those added later through [`registerProvider`](/ecosystem/appkit/reference/appkit#registerprovider)). Subscribes to [`watchCryptoOnrampProviders`](/ecosystem/appkit/reference/appkit#watchcryptoonrampproviders) and re-reads via [`getCryptoOnrampProviders`](/ecosystem/appkit/reference/appkit#getcryptoonrampproviders) so the array stays in sync. + +Returns: UseCryptoOnrampProvidersReturnType — Array of registered crypto-onramp providers. + +#### useCryptoOnrampQuote + +Quote a crypto-to-TON onramp — given a source asset/chain and the target TON asset, returns the rate, expected amount and the provider-specific metadata required to feed [`useCreateCryptoOnrampDeposit`](#usecreatecryptoonrampdeposit). `data` is the [`CryptoOnrampQuote`](/ecosystem/appkit/reference/appkit#cryptoonrampquote) payload. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseCryptoOnrampQuoteParameters`](#usecryptoonrampquoteparameters) | Quote inputs and TanStack Query overrides. | +| `parameters.amount` | `string` | Amount to onramp (either source or target crypto, depending on isSourceAmount) | +| `parameters.sourceCurrencyAddress` | `string` | Source crypto currency address (contract address or 0x0... for native) | +| `parameters.sourceChain` | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | +| `parameters.targetCurrencyAddress` | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | +| `parameters.recipientAddress` | `string` | TON address that will receive the target crypto | +| `parameters.refundAddress` | `string` | Refund address for the source crypto | +| `parameters.isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | +| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `parameters.providerId` | `string` | Provider to quote against. Defaults to the registered default provider. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseCryptoOnrampQuoteReturnType<selectData = GetCryptoOnrampQuoteData> — TanStack Query result for the quote read. + +#### useCryptoOnrampStatus + +Read the current status of a crypto-onramp deposit previously created via [`useCreateCryptoOnrampDeposit`](#usecreatecryptoonrampdeposit). Typically polled via `refetchInterval` until `data` reaches a terminal state — `'success'` (delivered to the recipient) or `'failed'` (provider could not complete the deposit). + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseCryptoOnrampStatusParameters`](#usecryptoonrampstatusparameters) | Deposit id, originating provider id and TanStack Query overrides. | +| `parameters.depositId` | `string` | Deposit id | +| `parameters.providerId` | `string` | Identifier of the provider that issued this deposit | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseCryptoOnrampStatusReturnType<selectData = GetCryptoOnrampStatusData> — TanStack Query result for the status read. + +### Jettons + +#### useJettonBalanceByAddress + +React hook reading a jetton balance for a given owner through TanStack Query — derives the owner's jetton-wallet address from the master and formats the balance using the supplied decimals. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseJettonBalanceByAddressParameters`](#usejettonbalancebyaddressparameters) | Jetton master, owner address, decimals, optional network override and TanStack Query overrides. | +| `parameters.jettonAddress` | UserFriendlyAddress | Jetton master contract address (the token, not the user's wallet for it). | +| `parameters.ownerAddress` | UserFriendlyAddress | Owner of the jetton wallet — typically the connected user's address. | +| `parameters.jettonDecimals` | `number` | Decimals declared by the jetton master. Used to format the raw balance into a human-readable string. | +| `parameters.network` | Network | Network to read the balance from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseJettonBalanceByAddressReturnType<selectData = GetJettonBalanceByAddressData> — TanStack Query result for the jetton balance read. + +**Example** + +```tsx +const { + data: balance, + isLoading, + error, +} = useJettonBalanceByAddress({ + ownerAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + jettonAddress: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiXme1Xc56Iwobkzgnjj', +}); + +if (isLoading) { + return
          Loading...
          ; +} + +if (error) { + return
          Error: {error.message}
          ; +} + +return
          Jetton Balance: {balance}
          ; +``` + +#### useJettonInfo + +React hook reading jetton-master metadata (name, symbol, decimals, image, description) through TanStack Query. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseJettonInfoParameters`](#usejettoninfoparameters) | Jetton master address, optional network override and TanStack Query overrides. | +| `parameters.address` | UserFriendlyAddress | Jetton master contract address whose metadata is being fetched. | +| `parameters.network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseJettonInfoReturnType<selectData = GetJettonInfoData> — TanStack Query result for the jetton info read. + +**Example** + +```tsx +const { + data: info, + isLoading, + error, +} = useJettonInfo({ + address: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiXme1Xc56Iwobkzgnjj', +}); + +if (isLoading) { + return
          Loading...
          ; +} + +if (error) { + return
          Error: {error.message}
          ; +} + +return ( +
          +

          Jetton Info

          +

          Name: {info?.name}

          +

          Symbol: {info?.symbol}

          +

          Decimals: {info?.decimals}

          +
          +); +``` + +#### useJettonWalletAddress + +React hook deriving the owner's jetton-wallet address — the per-owner contract that actually holds the jetton balance for a given master — through TanStack Query. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseJettonWalletAddressParameters`](#usejettonwalletaddressparameters) | Jetton master, owner address, optional network override and TanStack Query overrides. | +| `parameters.jettonAddress` | UserFriendlyAddress | Jetton master contract address. | +| `parameters.ownerAddress` | UserFriendlyAddress | Owner whose jetton wallet should be derived. | +| `parameters.network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: `UseQueryReturnType` — TanStack Query result for the jetton-wallet address read. + +**Example** + +```tsx +const { + data: walletAddress, + isLoading, + error, +} = useJettonWalletAddress({ + ownerAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + jettonAddress: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiXme1Xc56Iwobkzgnjj', +}); + +if (isLoading) { + return
          Loading...
          ; +} + +if (error) { + return
          Error: {error.message}
          ; +} + +return
          Jetton Wallet Address: {walletAddress}
          ; +``` + +#### useJettons + +React hook listing jettons held by the currently selected wallet through TanStack Query — auto-resolves the wallet address (use [`useJettonsByAddress`](#usejettonsbyaddress) for an arbitrary address). + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseJettonsParameters`](#usejettonsparameters) | TanStack Query overrides (`select`, `enabled`, `staleTime`, …), pagination and an optional network override. | +| `parameters.address` | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `parameters.network` | Network | Network to read the jettons from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.limit` | `number` | Maximum number of jettons to return. | +| `parameters.offset` | `number` | Number of jettons to skip before returning results — used for pagination. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseJettonsReturnType<selectData = GetJettonsByAddressData> — TanStack Query result for the jettons list. + +**Example** + +```tsx +const { data: jettons, isLoading, error } = useJettons(); + +if (isLoading) { + return
          Loading...
          ; +} + +if (error) { + return
          Error: {error.message}
          ; +} + +return ( +
          +

          Jettons

          +
            + {jettons?.jettons.map((jetton) => ( +
          • + {jetton.info.name}: {jetton.balance} +
          • + ))} +
          +
          +); +``` + +#### useJettonsByAddress + +React hook listing jettons held by an arbitrary address through TanStack Query — useful for wallets that aren't selected in AppKit (use [`useJettons`](#usejettons) for the selected wallet). + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseJettonsByAddressParameters`](#usejettonsbyaddressparameters) | Owner address, optional network override, pagination and TanStack Query overrides. | +| `parameters.address` | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `parameters.network` | Network | Network to read the jettons from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.limit` | `number` | Maximum number of jettons to return. | +| `parameters.offset` | `number` | Number of jettons to skip before returning results — used for pagination. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseJettonsByAddressReturnType<selectData = GetJettonsByAddressData> — TanStack Query result for the jettons list. + +**Example** + +```tsx +const { + data: jettons, + isLoading, + error, +} = useJettonsByAddress({ + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', +}); + +if (isLoading) { + return
          Loading...
          ; +} + +if (error) { + return
          Error: {error.message}
          ; +} + +return ( +
          +

          Jettons

          +
            + {jettons?.jettons.map((jetton) => ( +
          • + {jetton.info.name}: {jetton.balance} +
          • + ))} +
          +
          +); +``` + +#### useTransferJetton + +Transfer a jetton from the selected wallet in one step — derives the owner's jetton-wallet from the master address, builds the transfer message, signs it through the wallet and broadcasts it. Call `mutate` with the `jettonAddress` (master), the `recipientAddress`, an `amount` (in jetton units as a human-readable decimal — converted into raw smallest units using `jettonDecimals`), the `jettonDecimals` itself and an optional `comment`. On success, `data` carries the BoC and normalized hash of the broadcast transaction. Throws `Error('Wallet not connected')` if no wallet is currently selected — TanStack Query surfaces it via the mutation's `error`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseTransferJettonParameters`](#usetransferjettonparameters) | TanStack Query mutation overrides. | +| `parameters.mutation` | [`MutationOptionsOverride`](/ecosystem/appkit/reference/appkit#mutationoptionsoverride) | TanStack Query mutation options forwarded to `useMutation` (`onSuccess`, `onError`, `onMutate`, `retry`, …). `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper. | + +Returns: UseTransferJettonReturnType<context = unknown> — Mutation result for the jetton transfer call. + +**Example** + +```tsx +const { mutate: transfer, isPending, error } = useTransferJetton(); + +const handleTransfer = () => { + transfer({ + recipientAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + amount: '100', // 100 USDT + jettonAddress: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs', + jettonDecimals: 6, + }); +}; + +return ( +
          + + {error &&
          Error: {error.message}
          } +
          +); +``` + +#### useWatchJettons + +Subscribe to jetton-balance updates for the currently selected wallet. Updates flow into the TanStack Query cache so [`useJettons`](#usejettons) picks up the new data automatically (use [`useWatchJettonsByAddress`](#usewatchjettonsbyaddress) for a fixed address). Requires a streaming provider registered for the network — the hook exits silently with a console warning when none is configured. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseWatchJettonsParameters`](#usewatchjettonsparameters) | Update callback and optional network override. | +| `parameters.onChange` | (update: JettonUpdate) => void | Callback fired on every jetton-balance update from the streaming provider. | +| `parameters.network` | Network | Network to watch on. Defaults to the selected wallet's network. | + +Returns: `void`. + +**Example** + +```tsx +const { data: jettons } = useJettons(); + +useWatchJettons(); + +return ( +
          +

          Your Jettons:

          +
            + {jettons?.jettons.map((j) => ( +
          • + {j.info.name}: {j.balance} +
          • + ))} +
          +
          +); +``` + +#### useWatchJettonsByAddress + +Subscribe to jetton-balance updates for an arbitrary owner address. Updates flow into the TanStack Query cache so [`useJettonsByAddress`](#usejettonsbyaddress) and [`useJettonBalanceByAddress`](#usejettonbalancebyaddress) pick up the new data automatically. Requires a streaming provider registered for the network — the hook exits silently with a console warning when none is configured. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters`\* | [`UseWatchJettonsByAddressParameters`](#usewatchjettonsbyaddressparameters) | Owner address, update callback and optional network override. | +| `parameters.address` | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `parameters.onChange` | (update: JettonUpdate) => void | Callback fired on every jetton-balance update from the streaming provider. | +| `parameters.network` | Network | Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +Returns: `void`. + +**Example** + +```tsx +const address = 'UQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJKZ'; +const { data: jettons } = useJettonsByAddress({ address }); + +useWatchJettonsByAddress({ address }); + +return ( +
          +

          Jettons for {address}:

          +
            + {jettons?.jettons.map((j) => ( +
          • + {j.info.name}: {j.balance} +
          • + ))} +
          +
          +); +``` + +### NFTs + +#### useNft + +React hook reading metadata and ownership for a single NFT through TanStack Query, keyed by its contract address. `data` is `null` when the indexer has no record. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseNftParameters`](#usenftparameters) | NFT address, optional network override, and TanStack Query overrides. | +| `parameters.address` | UserFriendlyAddress \| Address | NFT contract address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `parameters.network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseNftReturnType<selectData = GetNftData> — TanStack Query result for the NFT read. + +**Example** + +```tsx +const { + data: nft, + isLoading, + error, +} = useNft({ + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', +}); + +if (isLoading) { + return
          Loading...
          ; +} + +if (error) { + return
          Error: {error.message}
          ; +} + +return ( +
          +

          NFT Details

          +

          Name: {nft?.info?.name}

          +

          Collection: {nft?.collection?.name}

          +

          Owner: {nft?.ownerAddress}

          +
          +); +``` + +#### useNfts + +React hook that reads NFTs held by the currently selected wallet through TanStack Query — auto-resolves the wallet address (use [`useNftsByAddress`](#usenftsbyaddress) for an arbitrary address). + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseNFTsParameters`](#usenftsparameters) | Optional pagination, network override, and TanStack Query overrides. | +| `parameters.address` | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `parameters.network` | Network | Network to read NFTs from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.limit` | `number` | Maximum number of NFTs to return. | +| `parameters.offset` | `number` | Number of NFTs to skip before returning results — used for pagination. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseNFTsReturnType<selectData = GetNFTsData> — TanStack Query result for the NFTs read. + +**Example** + +```tsx +const { + data: nfts, + isLoading, + error, +} = useNfts({ + limit: 10, +}); + +if (isLoading) { + return
          Loading...
          ; +} + +if (error) { + return
          Error: {error.message}
          ; +} + +return ( +
          +

          My NFTs

          +
            + {nfts?.nfts.map((nft) => ( +
          • + {nft.info?.name} ({nft.collection?.name}) +
          • + ))} +
          +
          +); +``` + +#### useNftsByAddress + +React hook that reads NFTs held by an arbitrary address through TanStack Query — useful for wallets that aren't selected in AppKit (use [`useNfts`](#usenfts) for the selected wallet). + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseNFTsByAddressParameters`](#usenftsbyaddressparameters) | Owner address, optional pagination and network override, plus TanStack Query overrides. | +| `parameters.address` | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `parameters.network` | Network | Network to read NFTs from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.limit` | `number` | Maximum number of NFTs to return. | +| `parameters.offset` | `number` | Number of NFTs to skip before returning results — used for pagination. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseNFTsByAddressReturnType<selectData = GetNFTsData> — TanStack Query result for the NFTs read. + +**Example** + +```tsx +const { + data: nfts, + isLoading, + error, +} = useNftsByAddress({ + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + limit: 10, +}); + +if (isLoading) { + return
          Loading...
          ; +} + +if (error) { + return
          Error: {error.message}
          ; +} + +return ( +
          +

          NFTs

          +
            + {nfts?.nfts.map((nft) => ( +
          • + {nft.info?.name} ({nft.collection?.name}) +
          • + ))} +
          +
          +); +``` + +#### useTransferNft + +Transfer an NFT from the selected wallet in one step — builds the ownership-transfer message and broadcasts it. Call `mutate` with an `nftAddress`, the `recipientAddress`, an optional `amount` (the TON attached for gas — defaults to AppKit's NFT gas-fee constant when omitted) and an optional `comment`. On success, `data` carries the BoC and normalized hash of the broadcast transaction. Throws `Error('Wallet not connected')` if no wallet is currently selected — TanStack Query surfaces it via the mutation's `error`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseTransferNftParameters`](#usetransfernftparameters) | TanStack Query mutation overrides. | +| `parameters.mutation` | [`MutationOptionsOverride`](/ecosystem/appkit/reference/appkit#mutationoptionsoverride) | TanStack Query mutation options forwarded to `useMutation` (`onSuccess`, `onError`, `onMutate`, `retry`, …). `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper. | + +Returns: UseTransferNftReturnType<context = unknown> — Mutation result for the transfer call. + +**Example** + +```tsx +const { mutate: transfer, isPending, error } = useTransferNft(); + +const handleTransfer = () => { + transfer({ + nftAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + recipientAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + comment: 'Gift for you', + }); +}; + +return ( +
          + + {error &&
          Error: {error.message}
          } +
          +); +``` + +### Networks + +#### useBlockNumber + +React hook reading the latest masterchain seqno through TanStack Query — useful for freshness checks and pagination cursors. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseBlockNumberParameters`](#useblocknumberparameters) | TanStack Query overrides and optional network. | +| `parameters.network` | Network | Network to query. Defaults to mainnet when omitted. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseBlockNumberReturnType<selectData = GetBlockNumberData> — TanStack Query result for the seqno read. + +#### useDefaultNetwork + +Read and write AppKit's default network — the network connectors use for new wallet connections. Returns a `useState`-style tuple. The read side updates when the default changes through any source (this hook, [`setDefaultNetwork`](/ecosystem/appkit/reference/appkit#setdefaultnetwork), manager events). + +Returns: UseDefaultNetworkReturnType — Tuple `[network, setNetwork]`. + +#### useNetwork + +Read the [`Network`](/ecosystem/appkit/reference/appkit#network) the selected wallet is connected to. Updates when the wallet's network changes (e.g. user switches mainnet/testnet inside the wallet). + +Returns: UseNetworkReturnType — Selected wallet's network, or `undefined` when no wallet is selected. + +#### useNetworks + +Read the list of networks configured on AppKit. Updates when [`AppKitNetworkManager`](/ecosystem/appkit/reference/appkit#appkitnetworkmanager) adds, replaces or drops a network. + +Returns: UseNetworksReturnType — Array of configured [`Network`](/ecosystem/appkit/reference/appkit#network)s. + +### Settings + +#### useAppKit + +Read the [`AppKit`](/ecosystem/appkit/reference/appkit#appkit) instance hosted by [`AppKitProvider`](#appkitprovider). Throws when the hook is rendered outside the provider tree. + +Returns: AppKit — The AppKit instance shared with descendant hooks/components. + +#### useAppKitTheme + +State hook that mirrors the active appkit-react theme to `document.body[data-ta-theme]` — returns a `[theme, setTheme]` tuple just like `useState`. + +Returns: `readonly [string, Dispatch>]` — Tuple `[theme, setTheme]` for reading and switching the active theme. + +#### useI18n + +Read the i18n context published by [`I18nProvider`](#i18nprovider) (or the wrapping [`AppKitProvider`](#appkitprovider)). Returns the active locale, translation function and helpers to switch locales or merge dictionaries. Throws when rendered outside the provider tree. + +Returns: I18nContextType — The i18n context ([`I18nContextType`](#i18ncontexttype)) with `activeLocale`, `t`, `locale` and `addDict`. + +### Signing + +#### useSignBinary + +Ask the selected wallet to sign an opaque binary blob (Base64-encoded), without on-chain structure. Call `mutate` from an event handler with the `bytes` to sign and an optional `network` override. On success, `data` carries the signature plus the signer address, timestamp and dApp domain the wallet bound to the signature. Throws `Error('Wallet not connected')` if no wallet is currently selected — TanStack Query surfaces it via the mutation's `error`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseSignBinaryParameters`](#usesignbinaryparameters) | TanStack Query mutation overrides. | +| `parameters.mutation` | [`MutationOptionsOverride`](/ecosystem/appkit/reference/appkit#mutationoptionsoverride) | TanStack Query mutation options forwarded to `useMutation` (`onSuccess`, `onError`, `onMutate`, `retry`, …). `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper. | + +Returns: UseSignBinaryReturnType<context = unknown> — Mutation result for the signing call. + +#### useSignCell + +Ask the selected wallet to sign a TON cell — typically so the signature can later be verified on-chain by a contract. Call `mutate` from an event handler with the `cell` content, a TL-B-style `schema` (used by the wallet to render the payload to the user before signing) and an optional `network` override. On success, `data` carries the signature plus the signer address, timestamp and dApp domain. Throws `Error('Wallet not connected')` if no wallet is currently selected — TanStack Query surfaces it via the mutation's `error`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseSignCellParameters`](#usesigncellparameters) | TanStack Query mutation overrides. | +| `parameters.mutation` | [`MutationOptionsOverride`](/ecosystem/appkit/reference/appkit#mutationoptionsoverride) | TanStack Query mutation options forwarded to `useMutation` (`onSuccess`, `onError`, `onMutate`, `retry`, …). `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper. | + +Returns: UseSignCellReturnType<context = unknown> — Mutation result for the signing call. + +#### useSignText + +Ask the selected wallet to sign a plain-text message — useful for off-chain login proofs and signed challenges. Call `mutate` from an event handler with the `text` to sign and an optional `network` override. On success, `data` carries the signature plus the canonicalized signer address, timestamp and dApp domain the wallet bound to the signature. Throws `Error('Wallet not connected')` if no wallet is currently selected — TanStack Query surfaces it via the mutation's `error`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseSignTextParameters`](#usesigntextparameters) | TanStack Query mutation overrides. | +| `parameters.mutation` | [`MutationOptionsOverride`](/ecosystem/appkit/reference/appkit#mutationoptionsoverride) | TanStack Query mutation options forwarded to `useMutation` (`onSuccess`, `onError`, `onMutate`, `retry`, …). `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper. | + +Returns: UseSignTextReturnType<context = unknown> — Mutation result for the signing call. + +### Staking + +#### useBuildStakeTransaction + +Build a stake/unstake [`TransactionRequest`](/ecosystem/appkit/reference/appkit#transactionrequest) from a [`StakingQuote`](/ecosystem/appkit/reference/appkit#stakingquote) (obtained via [`useStakingQuote`](#usestakingquote)) without sending it — lets the UI inspect, batch, or pass the request to [`useSendTransaction`](#usesendtransaction) separately. Call `mutate(params)` where `params` matches [`BuildStakeTransactionOptions`](/ecosystem/appkit/reference/appkit#buildstaketransactionoptions) (quote + user address, optional provider override). The resulting `TransactionRequest` is in `data` once the mutation resolves. + +Returns: UseBuildStakeTransactionReturnType<context = unknown> — Mutation result for the build call. + +#### useStakedBalance + +React hook reading a user's staked balance from a staking provider through TanStack Query — total staked plus, depending on the provider, any instant-unstake balance available right now. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseStakedBalanceParameters`](#usestakedbalanceparameters) | Owner address, optional `providerId`, optional network override, and TanStack Query overrides. | +| `parameters.userAddress` | UserFriendlyAddress | Owner whose staked balance should be read. | +| `parameters.network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.providerId` | `string` | Provider to query. Defaults to the registered default staking provider. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseStakedBalanceReturnType<selectData = GetStakedBalanceData> — TanStack Query result for the staked-balance read. + +#### useStakingContext + +Reads the [`StakingContextType`](#stakingcontexttype) from the nearest [`StakingWidgetProvider`](#stakingwidgetprovider) (or [`StakingWidget`](#stakingwidget)). Outside a provider, returns the default context (empty inputs, no-op actions) so a custom UI can still mount without crashing. + +Returns: StakingContextType. + +#### useStakingProvider + +React hook returning a registered staking provider. Subscribes to provider-registry changes via [`watchStakingProviders`](/ecosystem/appkit/reference/appkit#watchstakingproviders) and looks up by `id`, or returns the registered default when no id is given. Returns `undefined` when no provider matches and no default has been registered (where the underlying [`getStakingProvider`](/ecosystem/appkit/reference/appkit#getstakingprovider) action would throw). + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseStakingProviderParameters`](#usestakingproviderparameters) | Optional provider id. | +| `parameters.id` | `string` | Provider ID to look up. When omitted, returns the registered default staking provider. | + +Returns: UseStakingProviderReturnType — Matching staking provider instance, or `undefined` when none resolves. + +#### useStakingProviderInfo + +React hook reading live staking-pool info for a provider through TanStack Query — APY, instant-unstake liquidity and (for liquid staking) the current exchange rate. Use [`useStakingProviderMetadata`](#usestakingprovidermetadata) for static metadata (name, stake/receive tokens, supported unstake modes). Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseStakingProviderInfoParameters`](#usestakingproviderinfoparameters) | Optional `providerId`, network override, and TanStack Query overrides. | +| `parameters.network` | Network | Network whose staking pool should be inspected. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.providerId` | `string` | Provider to query. Defaults to the registered default staking provider. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseStakingProviderInfoReturnType<selectData = GetStakingProviderInfoData> — TanStack Query result for the live provider info. + +#### useStakingProviderMetadata + +Read static metadata for a staking provider — display name, stake/receive tokens, supported unstake modes and contract address. Returns `undefined` when no provider matches and no default is registered. Use [`useStakingProviderInfo`](#usestakingproviderinfo) for live values (APY, instant-unstake liquidity, exchange rate). Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseStakingProviderMetadataParameters`](#usestakingprovidermetadataparameters) | Optional `providerId` and network override. | +| `parameters.network` | Network | Network whose provider metadata should be read. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `parameters.providerId` | `string` | Provider to query. Defaults to the registered default staking provider. | + +Returns: StakingProviderMetadata \| undefined — Static [`StakingProviderMetadata`](/ecosystem/appkit/reference/appkit#stakingprovidermetadata), or `undefined` when the provider can't be resolved. + +#### useStakingProviders + +React hook returning every staking provider registered on the AppKit instance (both those passed via config and those added later). Subscribes to provider-registry changes via [`watchStakingProviders`](/ecosystem/appkit/reference/appkit#watchstakingproviders). + +Returns: UseStakingProvidersReturnType — Array of registered staking providers. + +#### useStakingQuote + +Quote a stake or unstake — given an amount, direction (`'stake'` / `'unstake'`) and the target asset, returns the rate, expected output and the provider-specific metadata required to feed [`useBuildStakeTransaction`](#usebuildstaketransaction). `data` is the [`StakingQuote`](/ecosystem/appkit/reference/appkit#stakingquote) payload. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseStakingQuoteParameters`](#usestakingquoteparameters) | Quote parameters, optional `providerId`, optional network override, and TanStack Query overrides. | +| `parameters.direction` | StakingQuoteDirection | Direction of the quote (stake or unstake) | +| `parameters.amount` | `string` | Amount of tokens to stake or unstake | +| `parameters.userAddress` | UserFriendlyAddress | Address of the user | +| `parameters.network` | Network | Network on which the staking will be executed | +| `parameters.unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](/ecosystem/appkit/reference/appkit#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | +| `parameters.isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | +| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `parameters.providerId` | `string` | Provider to quote against. Defaults to the registered default staking provider. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseStakingQuoteReturnType<selectData = GetStakingQuoteData> — TanStack Query result for the quote read. + +### Swap + +#### useBuildSwapTransaction + +Build a swap [`TransactionRequest`](/ecosystem/appkit/reference/appkit#transactionrequest) from a [`SwapQuote`](/ecosystem/appkit/reference/appkit#swapquote) (obtained via [`useSwapQuote`](#useswapquote)) without sending it — lets the UI inspect, batch, or pass the request to [`useSendTransaction`](#usesendtransaction) separately. Call `mutate(params)` where `params` matches [`BuildSwapTransactionOptions`](/ecosystem/appkit/reference/appkit#buildswaptransactionoptions) (quote, user address, optional slippage/deadline overrides). The resulting `TransactionRequest` is in `data` once the mutation resolves. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseBuildSwapTransactionParameters`](#usebuildswaptransactionparameters) | TanStack Query mutation overrides. | +| `parameters.mutation` | [`MutationOptionsOverride`](/ecosystem/appkit/reference/appkit#mutationoptionsoverride) | TanStack Query mutation options forwarded to `useMutation` (`onSuccess`, `onError`, `onMutate`, `retry`, …). `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper. | + +Returns: UseBuildSwapTransactionReturnType<context = unknown> — Mutation result for the build call. + +#### useSwapContext + +Reads the [`SwapContextType`](#swapcontexttype) populated by the nearest [`SwapWidgetProvider`](#swapwidgetprovider) (or the [`SwapWidget`](#swapwidget) that mounts one). Outside a provider it returns the no-op default value. + +Returns: SwapContextType. + +#### useSwapProvider + +Read and switch the default swap provider — subscribes to [`watchSwapProviders`](/ecosystem/appkit/reference/appkit#watchswapproviders) and re-reads via [`getSwapProvider`](/ecosystem/appkit/reference/appkit#getswapprovider). Returns a `useState`-style tuple. The read swallows the throw from [`getSwapProvider`](/ecosystem/appkit/reference/appkit#getswapprovider) (which throws when no provider matches — or when no id is passed and no default has been registered) and yields `undefined` instead. + +Returns: UseSwapProviderReturnType — Tuple `[provider, setProviderId]`. + +#### useSwapProviders + +List every swap provider registered on the AppKit instance (both those passed via [`AppKitConfig`](/ecosystem/appkit/reference/appkit#appkitconfig)'s `providers` and those added later through [`registerProvider`](/ecosystem/appkit/reference/appkit#registerprovider)). Subscribes to [`watchSwapProviders`](/ecosystem/appkit/reference/appkit#watchswapproviders) and re-reads via [`getSwapProviders`](/ecosystem/appkit/reference/appkit#getswapproviders) so the array stays in sync. + +Returns: UseSwapProvidersReturnType — Array of registered swap providers. + +#### useSwapQuote + +Quote a swap — given source/target tokens and an amount, returns the rate, expected output and the provider-specific metadata required to feed [`useBuildSwapTransaction`](#usebuildswaptransaction). `data` is the [`SwapQuote`](/ecosystem/appkit/reference/appkit#swapquote) payload. The `network` field defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseSwapQuoteParameters`](#useswapquoteparameters) | Source and target tokens, amount, optional network/provider override, and TanStack Query overrides. | +| `parameters.amount` | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | +| `parameters.from` | SwapToken | Token to swap from | +| `parameters.to` | SwapToken | Token to swap to | +| `parameters.network` | Network | Network on which the swap will be executed | +| `parameters.slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | +| `parameters.maxOutgoingMessages` | `number` | Maximum number of outgoing messages | +| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `parameters.isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | +| `parameters.providerId` | `string` | Provider to quote against. Defaults to the registered default swap provider. | +| `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +Returns: UseSwapQuoteReturnType<selectData = GetSwapQuoteData> — TanStack Query result for the swap quote. + +### Transactions + +#### useSendTransaction + +Hand a pre-built [`TransactionRequest`](/ecosystem/appkit/reference/appkit#transactionrequest) to the selected wallet for signing and broadcast — typically the second step after a `buildX` / `createX` action (e.g. [`useBuildSwapTransaction`](#usebuildswaptransaction), [`useBuildStakeTransaction`](#usebuildstaketransaction)) produces the request. Call `mutate(request)`. On success, `data` carries the BoC and normalized hash of the broadcast transaction. Throws `Error('Wallet not connected')` if no wallet is currently selected — TanStack Query surfaces it via the mutation's `error`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseSendTransactionParameters`](#usesendtransactionparameters) | TanStack Query mutation overrides. | +| `parameters.mutation` | [`MutationOptionsOverride`](/ecosystem/appkit/reference/appkit#mutationoptionsoverride) | TanStack Query mutation options forwarded to `useMutation` (`onSuccess`, `onError`, `onMutate`, `retry`, …). `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper. | + +Returns: UseSendTransactionReturnType<context = unknown> — Mutation result for the send call. + +#### useTransactionStatus + +Poll the status of a sent transaction by its BoC or normalized hash. In TON a single external message triggers a tree of internal messages, so the transaction is `'completed'` only once the entire trace finishes — pair with `refetchInterval` to keep polling until `data.status` is `'completed'` or `'failed'`. Pass either `boc` or `normalizedHash` (not both). The underlying action throws `Error('Either boc or normalizedHash must be provided')` when neither is supplied — TanStack Query surfaces it via the query's `error`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters`\* | [`UseTransactionStatusParameters`](#usetransactionstatusparameters) | `boc` xor `normalizedHash`, optional network and TanStack Query overrides. | + +Returns: UseTransactionStatusReturnType<selectData = GetTransactionStatusData> — TanStack Query result for the status read. + +#### useTransferTon + +Send TON from the selected wallet in one step — builds the transfer message, hands it to the wallet for signing and broadcasts it. Call `mutate` with a `recipientAddress`, an `amount` (in TON as a human-readable decimal, converted to nano-TON internally) and any of the optional `comment` / `payload` / `stateInit` fields. On success, `data` carries the BoC and normalized hash of the broadcast transaction — pair with [`useTransactionStatus`](#usetransactionstatus) to poll the trace to completion. Throws `Error('Wallet not connected')` if no wallet is currently selected — TanStack Query surfaces it via the mutation's `error`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseTransferTonParameters`](#usetransfertonparameters) | TanStack Query mutation overrides. | +| `parameters.mutation` | [`MutationOptionsOverride`](/ecosystem/appkit/reference/appkit#mutationoptionsoverride) | TanStack Query mutation options forwarded to `useMutation` (`onSuccess`, `onError`, `onMutate`, `retry`, …). `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper. | + +Returns: UseTransferTonReturnType<context = unknown> — Mutation result for the transfer call. + +#### useWatchTransactions + +Subscribe to incoming-transaction events for the currently selected wallet (use [`useWatchTransactionsByAddress`](#usewatchtransactionsbyaddress) for a fixed address). Auto-rebinds when the user connects, switches or disconnects. Requires a streaming provider registered for the network — the hook exits silently with a console warning when none is configured. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseWatchTransactionsParameters`](#usewatchtransactionsparameters) | Update callback. | +| `parameters.onChange` | (update: TransactionsUpdate) => void | Callback fired on every transactions update from the streaming provider. | + +Returns: `void`. + +**Example** + +```tsx +const [lastUpdate, setLastUpdate] = useState(null); + +useWatchTransactions({ + onChange: (update) => { + setLastUpdate(update); + }, +}); + +return ( +
          + {lastUpdate ? ( +
          + Last update for: {lastUpdate.address} +
          + Transactions count: {lastUpdate.transactions.length} +
          + ) : ( + 'Waiting for transactions...' + )} +
          +); +``` + +#### useWatchTransactionsByAddress + +Subscribe to incoming-transaction events for an arbitrary address (use [`useWatchTransactions`](#usewatchtransactions) for the selected wallet). Requires a streaming provider registered for the network — the hook exits silently with a console warning when none is configured. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters`\* | [`UseWatchTransactionsByAddressParameters`](#usewatchtransactionsbyaddressparameters) | Address, update callback and optional network override. | +| `parameters.address` | UserFriendlyAddress \| Address | Address to watch — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `parameters.onChange` | (update: TransactionsUpdate) => void | Callback fired on every transactions update from the streaming provider. | +| `parameters.network` | Network | Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +Returns: `void`. + +**Example** + +```tsx +const address = 'UQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJKZ'; +const [lastUpdate, setLastUpdate] = useState(null); + +useWatchTransactionsByAddress({ + address, + onChange: (update) => { + setLastUpdate(update); + }, +}); + +return ( +
          + {lastUpdate ? ( +
          + New transactions for: {lastUpdate.address} +
          + Count: {lastUpdate.transactions.length} +
          + ) : ( + 'Waiting for transactions...' + )} +
          +); +``` + +### Wallets + +#### useAddress + +Read the user-friendly address of the currently selected wallet. Updates when the selection changes. + +Returns: UseAddressReturnType — Selected wallet's address, or `undefined` when none is selected. + +#### useConnect + +Open a registered connector's connection flow (e.g., the TonConnect modal) and await its completion. Call `mutate` from a Connect button with the `connectorId` of the connector to drive. Once the user finishes the flow the new wallet becomes available via [`useSelectedWallet`](#useselectedwallet) / [`useConnectedWallets`](#useconnectedwallets). Throws `Error('Connector with id "" not found')` when no connector with that id is registered — TanStack Query surfaces it via the mutation's `error`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseConnectParameters`](#useconnectparameters) | TanStack Query mutation overrides. | +| `parameters.mutation` | [`MutationOptionsOverride`](/ecosystem/appkit/reference/appkit#mutationoptionsoverride) | TanStack Query mutation options forwarded to `useMutation` (`onSuccess`, `onError`, `onMutate`, `retry`, …). `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper. | + +Returns: UseConnectReturnType<context = unknown> — Mutation result for the connect call. + +#### useConnectedWallets + +Read the list of currently connected wallets across all registered connectors. Updates when a wallet connects or disconnects. + +Returns: UseConnectedWalletsReturnType — Read-only array of [`WalletInterface`](/ecosystem/appkit/reference/appkit#walletinterface)s. + +#### useDisconnect + +Tear down the session on a registered connector, disconnecting whichever wallet it currently holds. Call `mutate` from a Log out / Disconnect button with the `connectorId` of the connector to tear down. Once it resolves the wallet drops out of [`useSelectedWallet`](#useselectedwallet) / [`useConnectedWallets`](#useconnectedwallets). Throws `Error('Connector with id "" not found')` when no connector with that id is registered — TanStack Query surfaces it via the mutation's `error`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `parameters` | [`UseDisconnectParameters`](#usedisconnectparameters) | TanStack Query mutation overrides. | +| `parameters.mutation` | [`MutationOptionsOverride`](/ecosystem/appkit/reference/appkit#mutationoptionsoverride) | TanStack Query mutation options forwarded to `useMutation` (`onSuccess`, `onError`, `onMutate`, `retry`, …). `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper. | + +Returns: UseDisconnectReturnType<context = unknown> — Mutation result for the disconnect call. + +#### useSelectedWallet + +Read and switch the wallet that AppKit treats as active — most action hooks ([`useBalance`](#usebalance), [`useSignText`](#usesigntext), [`useTransferTon`](#usetransferton)) target this wallet implicitly. Returns a `useState`-style tuple. + +Returns: UseSelectedWalletReturnType — Tuple `[wallet, setWalletId]`. + +## Component + +### Balances + +#### SendJettonButton + +Pre-wired button that builds a jetton transfer with [`createTransferJettonTransaction`](/ecosystem/appkit/reference/appkit#createtransferjettontransaction) and dispatches it through the standard `Send` flow on click — disabled until `recipientAddress`, `amount`, `jetton.address` and `jetton.decimals` are all set. Throws inside the click handler when `jetton.address` or `jetton.decimals` is missing. + +| Prop | Type | Description | +| --- | --- | --- | +| `recipientAddress`\* | `string` | Recipient address. | +| `amount`\* | `string` | Amount in jetton units as a human-readable decimal string. Converted to raw smallest units via `jetton.decimals`. | +| `jetton`\* | `{ address: string; symbol: string; decimals: number; }` | Jetton master metadata — `address` (master contract), `symbol` (rendered in the button label) and `decimals` (used to format `amount`). | +| `comment` | `string` | Optional human-readable comment attached to the transfer. | +| `text` | `ReactNode` | Override the button label. Defaults to "Send". | +| `size` | `ButtonSize` | Size class applied to the button. Pass `'unset'` to skip the size class entirely (no padding, no typography) — useful with `variant="unstyled"`. | +| `borderRadius` | `ButtonBorderRadius` | Border radius token. Defaults to a size-dependent value (`s` → `2xl`, `m` → `l`, `l` → `xl`). | +| `variant` | `ButtonVariant` | Visual variant. Use `'unstyled'` to opt out of all built-in styling — the consumer is fully responsible for visuals via `className`. The Button still provides ref forwarding, `disabled`/`loading` plumbing, and `icon`/`children` rendering. | +| `loading` | `boolean` | When true, renders a spinner instead of `icon`/`children` and disables the button. | +| `fullWidth` | `boolean` | When true, the button stretches to fill its container width. | +| `icon` | `ReactNode` | Optional leading icon rendered before `children` when not loading. | +| `children` | `(props: SendRenderProps) => ReactNode` | Custom render function — replaces the default button with the caller's UI. Receives the current send state and click handler via [`SendRenderProps`](#sendrenderprops). | +| `onError` | `(error: Error) => void` | Called when the wallet rejects the request or the send fails. Receives the raised `Error`. | +| `onSuccess` | (response: SendTransactionReturnType) => void | Called once the transaction is broadcast. Receives the wallet's [`SendTransactionReturnType`](/ecosystem/appkit/reference/appkit#sendtransactionreturntype) (BoC + normalized hash). | + +**Example** + +```tsx +return ( + console.log('Transaction sent:', result)} + onError={(error) => console.error('Transaction failed:', error)} + /> +); +``` + +#### SendTonButton + +Pre-wired button that builds a TON transfer with [`createTransferTonTransaction`](/ecosystem/appkit/reference/appkit#createtransfertontransaction) and dispatches it through the standard `Send` flow on click — disabled until both `recipientAddress` and `amount` are set. + +| Prop | Type | Description | +| --- | --- | --- | +| `recipientAddress`\* | `string` | Recipient address. | +| `amount`\* | `string` | Amount in TON as a human-readable decimal string (e.g., `"1.5"`). Converted to nano-TON internally. | +| `comment` | `string` | Optional human-readable comment attached to the transfer. | +| `text` | `ReactNode` | Override the button label. Defaults to "Send". | +| `size` | `ButtonSize` | Size class applied to the button. Pass `'unset'` to skip the size class entirely (no padding, no typography) — useful with `variant="unstyled"`. | +| `borderRadius` | `ButtonBorderRadius` | Border radius token. Defaults to a size-dependent value (`s` → `2xl`, `m` → `l`, `l` → `xl`). | +| `variant` | `ButtonVariant` | Visual variant. Use `'unstyled'` to opt out of all built-in styling — the consumer is fully responsible for visuals via `className`. The Button still provides ref forwarding, `disabled`/`loading` plumbing, and `icon`/`children` rendering. | +| `loading` | `boolean` | When true, renders a spinner instead of `icon`/`children` and disables the button. | +| `fullWidth` | `boolean` | When true, the button stretches to fill its container width. | +| `icon` | `ReactNode` | Optional leading icon rendered before `children` when not loading. | +| `children` | `(props: SendRenderProps) => ReactNode` | Custom render function — replaces the default button with the caller's UI. Receives the current send state and click handler via [`SendRenderProps`](#sendrenderprops). | +| `onError` | `(error: Error) => void` | Called when the wallet rejects the request or the send fails. Receives the raised `Error`. | +| `onSuccess` | (response: SendTransactionReturnType) => void | Called once the transaction is broadcast. Receives the wallet's [`SendTransactionReturnType`](/ecosystem/appkit/reference/appkit#sendtransactionreturntype) (BoC + normalized hash). | + +**Example** + +```tsx +return ( + console.log('Transaction sent:', result)} + onError={(error) => console.error('Transaction failed:', error)} + /> +); +``` + +### Crypto Onramp + +#### CryptoOnrampWidget + +Drop-in widget for buying TON-side tokens with a crypto payment from another chain — wraps [`CryptoOnrampWidgetProvider`](#cryptoonrampwidgetprovider) (which drives token/method selection, quote fetching, deposit creation and status polling) around [`CryptoOnrampWidgetUI`](#cryptoonrampwidgetui). Pass a `children` render function to swap in a fully custom UI while keeping the same provider state. + +| Prop | Type | Description | +| --- | --- | --- | +| `children` | (props: CryptoOnrampWidgetRenderProps) => ReactNode | Custom render function. When provided, replaces the default [`CryptoOnrampWidgetUI`](#cryptoonrampwidgetui) and is called with the full [`CryptoOnrampWidgetRenderProps`](#cryptoonrampwidgetrenderprops) (context state, actions and forwarded `
          ` props), so callers can build a fully custom UI on top of the same provider. | +| `tokens` | CryptoOnrampToken[] | Target tokens (what the user buys on TON). Defaults to a built-in list. | +| `tokenSections` | CryptoOnrampTokenSectionConfig[] | Optional section configs grouping `tokens` in the picker. | +| `paymentMethods` | CryptoPaymentMethod[] | Source crypto payment methods (what the user pays with on another chain). Defaults to a built-in list. | +| `methodSections` | PaymentMethodSectionConfig[] | Optional section configs grouping `paymentMethods` in the picker. | +| `chains` | Record<string, ChainInfo> | Custom CAIP-2 → chain display info overrides. Merged on top of the built-in defaults, so consumers only need to provide what they want to override or add — for example, a single entry keyed by `'eip155:42161'` with a `name` of `'Arbitrum'` and a `logo` URL. | +| `defaultTokenId` | `string` | ID of the target token pre-selected on mount. | +| `defaultMethodId` | `string` | ID of the source payment method pre-selected on mount. | + +**Example** + +```tsx +// Uses built-in defaults for tokens, payment methods and chain display info. +// Make sure a crypto-onramp provider (Layerswap / swaps.xyz) is registered on AppKit. +return ; +``` + +#### CryptoOnrampWidgetProvider + +Context provider that powers the crypto-to-TON onramp widget — wires together token/method selection state, quote fetching ([`useCryptoOnrampQuote`](#usecryptoonrampquote)), deposit creation ([`useCreateCryptoOnrampDeposit`](#usecreatecryptoonrampdeposit)), deposit status polling ([`useCryptoOnrampStatus`](#usecryptoonrampstatus)), the target-token balance and validation. Consumers read the state via [`useCryptoOnrampContext`](#usecryptoonrampcontext). + +| Prop | Type | Description | +| --- | --- | --- | +| `tokens` | CryptoOnrampToken[] | Target tokens (what the user buys on TON). Defaults to a built-in list. | +| `tokenSections` | CryptoOnrampTokenSectionConfig[] | Optional section configs grouping `tokens` in the picker. | +| `paymentMethods` | CryptoPaymentMethod[] | Source crypto payment methods (what the user pays with on another chain). Defaults to a built-in list. | +| `methodSections` | PaymentMethodSectionConfig[] | Optional section configs grouping `paymentMethods` in the picker. | +| `chains` | Record<string, ChainInfo> | Custom CAIP-2 → chain display info overrides. Merged on top of the built-in defaults, so consumers only need to provide what they want to override or add — for example, a single entry keyed by `'eip155:42161'` with a `name` of `'Arbitrum'` and a `logo` URL. | +| `defaultTokenId` | `string` | ID of the target token pre-selected on mount. | +| `defaultMethodId` | `string` | ID of the source payment method pre-selected on mount. | + +#### CryptoOnrampWidgetUI + +Presentational UI for the crypto-to-TON onramp widget — renders the from/to selectors, amount input with presets, continue button, info block (you-get / balance / provider) and the token-pick / method-pick / refund-address / deposit modals. All state and actions come from props ([`CryptoOnrampWidgetRenderProps`](#cryptoonrampwidgetrenderprops)). Typically rendered inside [`CryptoOnrampWidgetProvider`](#cryptoonrampwidgetprovider) via [`CryptoOnrampWidget`](#cryptoonrampwidget). + +| Prop | Type | Description | +| --- | --- | --- | +| `tokens`\* | CryptoOnrampToken[] | Full list of target tokens the user can buy. | +| `tokenSections` | CryptoOnrampTokenSectionConfig[] | Optional section configs grouping `tokens` in the picker. | +| `selectedToken`\* | CryptoOnrampToken \| null | Currently selected target token to buy. `null` until tokens load. | +| `setSelectedToken`\* | (token: CryptoOnrampToken) => void | Updates `selectedToken`. | +| `paymentMethods`\* | CryptoPaymentMethod[] | Available source crypto payment methods. | +| `methodSections` | PaymentMethodSectionConfig[] | Optional section configs grouping `paymentMethods` in the picker. | +| `selectedMethod`\* | CryptoPaymentMethod | Currently selected source payment method. | +| `setSelectedMethod`\* | (method: CryptoPaymentMethod) => void | Updates `selectedMethod`. | +| `chains`\* | Record<string, ChainInfo> | CAIP-2 → chain display info map (built-in defaults merged with consumer overrides). | +| `amount`\* | `string` | Current amount input value as a decimal string. | +| `setAmount`\* | `(value: string) => void` | Updates `amount`. | +| `amountInputMode`\* | CryptoAmountInputMode | Which side `amount` is denominated in — see [`CryptoAmountInputMode`](#cryptoamountinputmode). | +| `setAmountInputMode`\* | (mode: CryptoAmountInputMode) => void | Updates `amountInputMode`. | +| `convertedAmount`\* | `string` | Other side of `amount` after applying the current quote's rate. | +| `presetAmounts`\* | OnrampAmountPreset[] | Quick-pick amount buttons rendered in the widget. | +| `quote`\* | CryptoOnrampQuote \| null | Current quote, or `null` if not yet fetched / invalidated. | +| `isLoadingQuote`\* | `boolean` | Whether a quote is in flight (includes the input-debounce window). | +| `quoteError`\* | `string \| null` | Quote-side validation/fetch error as an i18n key, or `null`. | +| `quoteProviderName`\* | `string \| null` | Display name of the provider behind the current quote, when available. | +| `deposit`\* | CryptoOnrampDeposit \| null | Current deposit returned by the provider once `createDeposit` succeeded. | +| `isCreatingDeposit`\* | `boolean` | Whether `createDeposit` is in flight. | +| `depositError`\* | `string \| null` | Deposit-side error as an i18n key, or `null`. | +| `depositAmount`\* | `string` | Formatted deposit amount the user must send on the source chain. | +| `createDeposit`\* | `() => void` | Triggers deposit creation from the current quote. | +| `depositStatus`\* | CryptoOnrampStatus \| null | Latest deposit status polled via [`useCryptoOnrampStatus`](#usecryptoonrampstatus), or `null`. | +| `isRefundAddressRequired`\* | `boolean` | Whether the current quote provider requires a refund address before deposit. | +| `isReversedAmountSupported`\* | `boolean` | Whether the current quote provider supports reversed (target-amount) input. | +| `refundAddress`\* | `string` | Refund address the user typed, if `isRefundAddressRequired`. | +| `setRefundAddress`\* | `(address: string) => void` | Updates `refundAddress`. | +| `targetBalance`\* | `string` | Connected wallet's balance of the selected target token (formatted, token units). | +| `isLoadingTargetBalance`\* | `boolean` | Whether the target token balance is being fetched. | +| `isWalletConnected`\* | `boolean` | Whether a TON wallet is currently connected. | +| `canContinue`\* | `boolean` | Whether the user can proceed — valid amount, quote available, and wallet connected. | +| `onReset`\* | `() => void` | Invalidates the active quote and clears the deposit, returning the widget to its initial state. | + +### NFTs + +#### NftItem + +Card-style button rendering an NFT's image, name and collection name with an "On Sale" badge when applicable — falls back to a placeholder icon when the image is missing or fails to load. + +| Prop | Type | Description | +| --- | --- | --- | +| `nft`\* | NFT | NFT to render — name, collection name, image and on-sale state are derived via `getFormattedNftInfo`. | + +**Example** + +```tsx +return console.log('NFT clicked')} />; +``` + +### Providers + +#### AppKitProvider + +Top-level React provider that wires AppKit, the TonConnect bridge and i18n into the component tree — wrap your app once near the root so descendant hooks ([`useAppKit`](#useappkit), [`useBalance`](#usebalance), …) and components can resolve their context. + +| Prop | Type | Description | +| --- | --- | --- | +| `appKit`\* | AppKit | Runtime instance constructed at app startup. Shared across every appkit-react hook and component. | + +**Example** + +```tsx +return ( + +

          My App

          + {/* Your App Content */} +
          +); +``` + +#### I18nProvider + +React provider that mounts the i18n context for [`useI18n`](#usei18n) and child components — already wrapped by [`AppKitProvider`](#appkitprovider), so apps usually only render it directly when they need to override the locale or dictionaries. + +| Prop | Type | Description | +| --- | --- | --- | +| `locale` | `string` | Initial locale code. Defaults to the i18n library's default when omitted. | +| `lngDicts` | `Record` | Translation dictionaries keyed by locale. Loaded into the underlying i18n instance on mount. | + +**Example** + +```tsx +// Override the locale. Pass `lngDicts` with your own translations when you need them. +return ( + +
          My App
          +
          +); +``` + +### Shared + +#### AmountPresets + +Horizontal row of preset amount buttons — typically used next to an amount input to offer quick fills. + +| Prop | Type | Description | +| --- | --- | --- | +| `presets`\* | AmountPreset[] | Preset buttons to render, in order. | +| `currencySymbol` | `string` | Optional symbol (e.g., `"$"`) prepended to each preset label. | +| `onPresetSelect`\* | `(value: string) => void` | Called with the selected preset's `amount` unless the preset defines its own `onSelect`. | + +**Example** + +```tsx +return ( +
          + setAmount(e.target.value)} placeholder="Amount" /> + +
          +); +``` + +#### CopyButton + +Icon-only button that copies `value` to the clipboard on click and flips its icon to a checkmark for a short confirmation window. + +| Prop | Type | Description | +| --- | --- | --- | +| `value`\* | `string` | Text written to the clipboard when the button is clicked. | +| `aria-label`\* | `string` | Accessible label for screen readers. | + +**Example** + +```tsx +return ; +``` + +#### CurrencyItem + +Compound row used inside currency/token select lists: shows a token logo, name + ticker, optional verified badge, and an optional balance / under-balance on the right. Pass top-level props for the default layout, or pass `children` made of the sub-components for full control. + +**Members** + +| Member | Description | +| --- | --- | +| `CurrencyItem.Container` | Root ` +); +``` + +#### CenteredAmountInput + +Center-aligned, auto-resizing amount input with optional leading symbol and trailing ticker. Scales the font down to fit the container when the rendered text overflows, and clicking the wrapper focuses the input. + +| Prop | Type | Description | +| --- | --- | --- | +| `value`\* | `string` | Controlled input value (decimal string). | +| `onValueChange`\* | `(value: string) => void` | Called with the new string whenever the user edits the input. | +| `ticker` | `string` | Optional trailing ticker label (e.g., `'TON'`). | +| `symbol` | `string` | Optional leading currency symbol (e.g., `'$'`). | +| `placeholder` | `string` | Placeholder shown when `value` is empty. Defaults to `'0'`. | +| `disabled` | `boolean` | When true, the underlying `` is disabled. | + +**Example** + +```tsx +return ; +``` + +#### Collapsible + +Animated collapsible container — transitions its height between `0` and the content's natural height when `open` toggles. Sets `aria-hidden` to mirror the open state. + +| Prop | Type | Description | +| --- | --- | --- | +| `open`\* | `boolean` | When true, the content is expanded. When false, it is collapsed to zero height. | + +**Example** + +```tsx +return ( +
          + + +

          Hidden details about the transaction.

          +
          +
          +); +``` + +#### InfoBlock + +Compound component for rendering a stacked list of label/value rows (e.g., transaction details, settings summaries). Sub-components forward extra props to the underlying DOM element so callers can layer custom classes and handlers. + +**Members** + +| Member | Description | +| --- | --- | +| `InfoBlock.Container` | Outer wrapper — vertical container that hosts the rows. | +| `InfoBlock.Row` | Horizontal row that pairs a label with a value. | +| `InfoBlock.Label` | Label cell — typically the muted descriptor on the left. | +| `InfoBlock.Value` | Value cell — typically the emphasized content on the right. | +| `InfoBlock.LabelSkeleton` | Skeleton placeholder for a [`InfoBlock.Label`](#infoblock) while data is loading. Defaults to `width=64`, `height='1lh'`. | +| `InfoBlock.ValueSkeleton` | Skeleton placeholder for a [`InfoBlock.Value`](#infoblock) while data is loading. Defaults to `width=80`, `height='1lh'`. | + +**Example** + +```ts +return ( + + + Rate + 1 TON ≈ $5.43 + + + Network fee + 0.01 TON + + +); +``` + +#### Input + +Compound text-input component. Use the default export as the outer wrapper (it is the [`Input.Container`](#input)) and compose sub-components for the header, field, slots, control, and caption. State flags (`disabled`, `error`, `loading`, `resizable`, `size`) live on the container and are read by the inner control via context. + +**Members** + +| Member | Description | +| --- | --- | +| `Input.Container` | Outer wrapper that provides input context (size, variant, disabled, error, loading, resizable). | +| `Input.Header` | Header row above the field — holds the title and optional trailing controls. | +| `Input.Title` | Title text shown inside [`Input.Header`](#input). | +| `Input.Field` | Horizontal row that holds slots and the input control. | +| `Input.Slot` | Side-anchored slot used for adornments such as icons or buttons. | +| `Input.Input` | The actual `` control. Respects context flags and reads its size/variant from [`Input.Container`](#input). | +| `Input.Caption` | Caption / helper text below the field. Switches to error styling when the container has `error` set. | + +**Example** + +```tsx +return ( + + + Recipient + + + setValue(event.target.value)} placeholder="EQ..." /> + + Paste a TON wallet address. + +); +``` + +#### Logo + +Square logo / avatar primitive — renders an `` when `src` loads successfully, otherwise shows a text fallback (after a brief delay to avoid flicker). Useful for token icons, wallet avatars, and project logos. + +| Prop | Type | Description | +| --- | --- | --- | +| `size` | `number` | Square size in pixels for the rendered logo. Defaults to `30`. | +| `src` | `string` | Image URL to render. While loading or on failure, the fallback is shown. | +| `alt` | `string` | Alt text passed to the underlying ``. When `fallback` is not provided, its first character is shown as the fallback. If both are missing, no fallback is rendered. | +| `fallback` | `string` | Text shown in place of the image when `src` fails or is missing (defaults to the first character of `alt`). | + +**Example** + +```tsx +return ; +``` + +#### LogoWithNetwork + +Token logo with an overlaid network badge — wraps [`Logo`](#logo) and renders a smaller secondary logo as a corner badge to indicate which network the asset belongs to. + +| Prop | Type | Description | +| --- | --- | --- | +| `size` | `number` | Size of the main logo in pixels. Defaults to `30`. The network badge is sized to `size * 0.4`. | +| `src` | `string` | Image source for the main logo. | +| `alt` | `string` | Alt text for the main logo. | +| `fallback` | `string` | Fallback text shown when the main logo image fails or is missing. | +| `networkSrc` | `string` | Image source for the network badge overlay. When omitted, the badge is not rendered. | +| `networkAlt` | `string` | Alt text for the network badge. | + +**Example** + +```tsx +return ( + +); +``` + +#### Modal + +Centered modal dialog with a header (optional title + close button) and a scrollable body. Clicking the overlay closes the modal. Clicks on the content do not bubble through. + +| Prop | Type | Description | +| --- | --- | --- | +| `open` | `boolean` | Controlled open state. | +| `onOpenChange` | `(open: boolean) => void` | Called whenever the open state changes (e.g., via the close button, overlay click, or `Escape`). | +| `title` | `string` | Optional title rendered in the modal header. | +| `children` | `ReactNode` | Modal body content. | +| `className` | `string` | Additional class name applied to the content container. | +| `bodyClassName` | `string` | Additional class name applied to the body container. | + +**Example** + +```tsx +return ( +
          + + +

          Are you sure you want to proceed?

          +
          +
          +); +``` + +#### Select + +Compound select / dropdown component with controlled or uncontrolled state. The content is portaled to `document.body` and positioned relative to the trigger. Closes on outside click, `Escape`, or item selection. + +**Members** + +| Member | Description | +| --- | --- | +| `Select.Root` | Provider that owns the selected value and open state, controlled or uncontrolled. | +| `Select.Trigger` | [`Button`](#button)-based trigger that toggles the popover and exposes `aria-expanded`. | +| `Select.Content` | Portaled popover that renders the list of items. Positioned under the trigger with optional `sideOffset`. | +| `Select.Item` | Selectable option row. Commits its `value` to the root on click. | + +**Example** + +```ts +return ( + + {value === 'mainnet' ? 'Mainnet' : 'Testnet'} + + Mainnet + Testnet + + +); +``` + +#### Skeleton + +Animated placeholder block used while data is loading. Supply `width` / `height` to match the dimensions of the eventual content. + +| Prop | Type | Description | +| --- | --- | --- | +| `width` | `string \| number` | Width of the placeholder. Accepts any valid CSS length or a number (interpreted as pixels). | +| `height` | `string \| number` | Height of the placeholder. Accepts any valid CSS length or a number (interpreted as pixels). | + +**Example** + +```tsx +return ; +``` + +#### Tabs + +Root tabs container — owns the active value (controlled or uncontrolled) and shares it with descendant [`TabsList`](#tabslist), [`TabsTrigger`](#tabstrigger), and [`TabsContent`](#tabscontent) via context. + +| Prop | Type | Description | +| --- | --- | --- | +| `value` | `string` | Controlled active tab value. | +| `defaultValue` | `string` | Initial active tab when uncontrolled. Defaults to `''`. | +| `onValueChange` | `(value: string) => void` | Called whenever the active tab changes. | +| `children`\* | `ReactNode` | Compound sub-components — typically [`TabsList`](#tabslist) (with [`TabsTrigger`](#tabstrigger)s) followed by [`TabsContent`](#tabscontent)s. | + +**Example** + +```tsx +return ( + + + Stake + Unstake + + +

          Stake your TON to earn rewards.

          +
          + +

          Withdraw your staked TON.

          +
          +
          +); +``` + +#### TabsContent + +Tab panel rendered with `role="tabpanel"`. Returns `null` unless its `value` matches the active [`Tabs`](#tabs) value. + +| Prop | Type | Description | +| --- | --- | --- | +| `value`\* | `string` | Value this panel is associated with — rendered only when the parent [`Tabs`](#tabs) is on this value. | +| `children`\* | `ReactNode` | Panel content. | + +#### TabsList + +Horizontal list of tab triggers with `role="tablist"`. + +| Prop | Type | Description | +| --- | --- | --- | +| `children`\* | `ReactNode` | Tab triggers — typically one or more [`TabsTrigger`](#tabstrigger)s. | + +#### TabsTrigger + +Tab trigger button with `role="tab"`. Activates its `value` on click and reflects active state via `aria-selected` and `data-state`. + +| Prop | Type | Description | +| --- | --- | --- | +| `value`\* | `string` | Value committed to the parent [`Tabs`](#tabs) when this trigger is activated. | +| `children`\* | `ReactNode` | Trigger label / content. | + +#### TonIcon + +TON brand diamond glyph — solid, inherits color from `currentColor`. + +| Prop | Type | Description | +| --- | --- | --- | +| `size` | `number` | Square size of the icon in pixels. Defaults to [`DEFAULT_ICON_SIZE`](#default_icon_size). | + +#### TonIconCircle + +TON brand glyph rendered inside a filled circle, using the TON brand color token. + +| Prop | Type | Description | +| --- | --- | --- | +| `size` | `number` | Square size of the icon in pixels. Defaults to [`DEFAULT_ICON_SIZE`](#default_icon_size). | + +## Type + +### Balances + +#### SendJettonButtonProps + +Props accepted by [`SendJettonButton`](#sendjettonbutton) — extends the base `Send` button props (button text, sizing, callbacks) with the jetton-transfer details. + +| Field | Type | Description | +| --- | --- | --- | +| `recipientAddress`\* | `string` | Recipient address. | +| `amount`\* | `string` | Amount in jetton units as a human-readable decimal string. Converted to raw smallest units via `jetton.decimals`. | +| `jetton`\* | `{ address: string; symbol: string; decimals: number; }` | Jetton master metadata — `address` (master contract), `symbol` (rendered in the button label) and `decimals` (used to format `amount`). | +| `comment` | `string` | Optional human-readable comment attached to the transfer. | +| `text` | `ReactNode` | Override the button label. Defaults to "Send". | +| `size` | `ButtonSize` | Size class applied to the button. Pass `'unset'` to skip the size class entirely (no padding, no typography) — useful with `variant="unstyled"`. | +| `borderRadius` | `ButtonBorderRadius` | Border radius token. Defaults to a size-dependent value (`s` → `2xl`, `m` → `l`, `l` → `xl`). | +| `variant` | `ButtonVariant` | Visual variant. Use `'unstyled'` to opt out of all built-in styling — the consumer is fully responsible for visuals via `className`. The Button still provides ref forwarding, `disabled`/`loading` plumbing, and `icon`/`children` rendering. | +| `loading` | `boolean` | When true, renders a spinner instead of `icon`/`children` and disables the button. | +| `fullWidth` | `boolean` | When true, the button stretches to fill its container width. | +| `icon` | `ReactNode` | Optional leading icon rendered before `children` when not loading. | +| `children` | `(props: SendRenderProps) => ReactNode` | Custom render function — replaces the default button with the caller's UI. Receives the current send state and click handler via [`SendRenderProps`](#sendrenderprops). | +| `onError` | `(error: Error) => void` | Called when the wallet rejects the request or the send fails. Receives the raised `Error`. | +| `onSuccess` | (response: SendTransactionReturnType) => void | Called once the transaction is broadcast. Receives the wallet's [`SendTransactionReturnType`](/ecosystem/appkit/reference/appkit#sendtransactionreturntype) (BoC + normalized hash). | + +#### SendTonButtonProps + +Props accepted by [`SendTonButton`](#sendtonbutton) — extends the base `Send` button props (button text, sizing, callbacks) with the TON-transfer details. + +| Field | Type | Description | +| --- | --- | --- | +| `recipientAddress`\* | `string` | Recipient address. | +| `amount`\* | `string` | Amount in TON as a human-readable decimal string (e.g., `"1.5"`). Converted to nano-TON internally. | +| `comment` | `string` | Optional human-readable comment attached to the transfer. | +| `text` | `ReactNode` | Override the button label. Defaults to "Send". | +| `size` | `ButtonSize` | Size class applied to the button. Pass `'unset'` to skip the size class entirely (no padding, no typography) — useful with `variant="unstyled"`. | +| `borderRadius` | `ButtonBorderRadius` | Border radius token. Defaults to a size-dependent value (`s` → `2xl`, `m` → `l`, `l` → `xl`). | +| `variant` | `ButtonVariant` | Visual variant. Use `'unstyled'` to opt out of all built-in styling — the consumer is fully responsible for visuals via `className`. The Button still provides ref forwarding, `disabled`/`loading` plumbing, and `icon`/`children` rendering. | +| `loading` | `boolean` | When true, renders a spinner instead of `icon`/`children` and disables the button. | +| `fullWidth` | `boolean` | When true, the button stretches to fill its container width. | +| `icon` | `ReactNode` | Optional leading icon rendered before `children` when not loading. | +| `children` | `(props: SendRenderProps) => ReactNode` | Custom render function — replaces the default button with the caller's UI. Receives the current send state and click handler via [`SendRenderProps`](#sendrenderprops). | +| `onError` | `(error: Error) => void` | Called when the wallet rejects the request or the send fails. Receives the raised `Error`. | +| `onSuccess` | (response: SendTransactionReturnType) => void | Called once the transaction is broadcast. Receives the wallet's [`SendTransactionReturnType`](/ecosystem/appkit/reference/appkit#sendtransactionreturntype) (BoC + normalized hash). | + +#### UseBalanceByAddressParameters + +Parameters accepted by [`useBalanceByAddress`](#usebalancebyaddress) — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the target address and optional network override. + +| Field | Type | Description | +| --- | --- | --- | +| `address` | UserFriendlyAddress \| Address | Wallet address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `network` | Network | Network to read the balance from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +#### UseBalanceByAddressReturnType + +Return type of [`useBalanceByAddress`](#usebalancebyaddress) — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + +```ts +type UseBalanceByAddressReturnType = UseQueryReturnType< + selectData, + GetBalanceErrorType +>; +``` + +#### UseBalanceParameters + +Parameters accepted by [`useBalance`](#usebalance) — same shape as [`UseBalanceByAddressParameters`](#usebalancebyaddressparameters). The hook resolves `address` from the selected wallet and overrides any value supplied here. + +| Field | Type | Description | +| --- | --- | --- | +| `address` | UserFriendlyAddress \| Address | Wallet address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `network` | Network | Network to read the balance from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +#### UseBalanceReturnType + +Return type of [`useBalance`](#usebalance) — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + +```ts +type UseBalanceReturnType = UseBalanceByAddressReturnType; +``` + +#### UseWatchBalanceByAddressParameters + +Parameters accepted by [`useWatchBalanceByAddress`](#usewatchbalancebyaddress) — same fields as [`WatchBalanceByAddressOptions`](/ecosystem/appkit/reference/appkit#watchbalancebyaddressoptions), all optional so callers can render the hook before the address is known. + +```ts +type UseWatchBalanceByAddressParameters = Partial; +``` + +#### UseWatchBalanceParameters + +Parameters accepted by [`useWatchBalance`](#usewatchbalance) — same fields as [`UseWatchBalanceByAddressParameters`](#usewatchbalancebyaddressparameters) minus `address`, which the hook resolves from the selected wallet. + +```ts +type UseWatchBalanceParameters = Omit; +``` + +### Connectors + +#### UseConnectorsReturnType + +Return type of [`useConnectors`](#useconnectors) — same shape as [`GetConnectorsReturnType`](/ecosystem/appkit/reference/appkit#getconnectorsreturntype). + +```ts +type UseConnectorsReturnType = GetConnectorsReturnType; +``` + +### Crypto Onramp + +#### ChainInfo + +Display info for a CAIP-2 chain — used by the crypto onramp widget to render chain names and logos. + +| Field | Type | Description | +| --- | --- | --- | +| `name`\* | `string` | Human-readable chain name (e.g. `"Ethereum"`, `"Arbitrum One"`). | +| `logo` | `string` | Optional logo URL for the chain. | + +#### CryptoAmountInputMode + +Which side the amount input is currently denominated in — `token` means the user is entering the target-token amount, `method` means they are entering the source payment-method amount. + +```ts +type CryptoAmountInputMode = 'token' | 'method'; +``` + +#### CryptoOnrampContextType + +Shape of the `CryptoOnrampContext` value — selection state, quote/deposit data and actions exposed by [`CryptoOnrampWidgetProvider`](#cryptoonrampwidgetprovider) to the widget UI (and to custom render callbacks passed to [`CryptoOnrampWidget`](#cryptoonrampwidget)). + +| Field | Type | Description | +| --- | --- | --- | +| `tokens`\* | CryptoOnrampToken[] | Full list of target tokens the user can buy. | +| `tokenSections` | CryptoOnrampTokenSectionConfig[] | Optional section configs grouping `tokens` in the picker. | +| `selectedToken`\* | CryptoOnrampToken \| null | Currently selected target token to buy. `null` until tokens load. | +| `setSelectedToken`\* | (token: CryptoOnrampToken) => void | Updates `selectedToken`. | +| `paymentMethods`\* | CryptoPaymentMethod[] | Available source crypto payment methods. | +| `methodSections` | PaymentMethodSectionConfig[] | Optional section configs grouping `paymentMethods` in the picker. | +| `selectedMethod`\* | CryptoPaymentMethod | Currently selected source payment method. | +| `setSelectedMethod`\* | (method: CryptoPaymentMethod) => void | Updates `selectedMethod`. | +| `chains`\* | Record<string, ChainInfo> | CAIP-2 → chain display info map (built-in defaults merged with consumer overrides). | +| `amount`\* | `string` | Current amount input value as a decimal string. | +| `setAmount`\* | `(value: string) => void` | Updates `amount`. | +| `amountInputMode`\* | CryptoAmountInputMode | Which side `amount` is denominated in — see [`CryptoAmountInputMode`](#cryptoamountinputmode). | +| `setAmountInputMode`\* | (mode: CryptoAmountInputMode) => void | Updates `amountInputMode`. | +| `convertedAmount`\* | `string` | Other side of `amount` after applying the current quote's rate. | +| `presetAmounts`\* | OnrampAmountPreset[] | Quick-pick amount buttons rendered in the widget. | +| `quote`\* | CryptoOnrampQuote \| null | Current quote, or `null` if not yet fetched / invalidated. | +| `isLoadingQuote`\* | `boolean` | Whether a quote is in flight (includes the input-debounce window). | +| `quoteError`\* | `string \| null` | Quote-side validation/fetch error as an i18n key, or `null`. | +| `quoteProviderName`\* | `string \| null` | Display name of the provider behind the current quote, when available. | +| `deposit`\* | CryptoOnrampDeposit \| null | Current deposit returned by the provider once `createDeposit` succeeded. | +| `isCreatingDeposit`\* | `boolean` | Whether `createDeposit` is in flight. | +| `depositError`\* | `string \| null` | Deposit-side error as an i18n key, or `null`. | +| `depositAmount`\* | `string` | Formatted deposit amount the user must send on the source chain. | +| `createDeposit`\* | `() => void` | Triggers deposit creation from the current quote. | +| `depositStatus`\* | CryptoOnrampStatus \| null | Latest deposit status polled via [`useCryptoOnrampStatus`](#usecryptoonrampstatus), or `null`. | +| `isRefundAddressRequired`\* | `boolean` | Whether the current quote provider requires a refund address before deposit. | +| `isReversedAmountSupported`\* | `boolean` | Whether the current quote provider supports reversed (target-amount) input. | +| `refundAddress`\* | `string` | Refund address the user typed, if `isRefundAddressRequired`. | +| `setRefundAddress`\* | `(address: string) => void` | Updates `refundAddress`. | +| `targetBalance`\* | `string` | Connected wallet's balance of the selected target token (formatted, token units). | +| `isLoadingTargetBalance`\* | `boolean` | Whether the target token balance is being fetched. | +| `isWalletConnected`\* | `boolean` | Whether a TON wallet is currently connected. | +| `canContinue`\* | `boolean` | Whether the user can proceed — valid amount, quote available, and wallet connected. | +| `onReset`\* | `() => void` | Invalidates the active quote and clears the deposit, returning the widget to its initial state. | + +#### CryptoOnrampProviderProps + +Props for [`CryptoOnrampWidgetProvider`](#cryptoonrampwidgetprovider) — configures the target tokens and payment methods exposed to the widget, plus optional chain display overrides. + +| Field | Type | Description | +| --- | --- | --- | +| `tokens` | CryptoOnrampToken[] | Target tokens (what the user buys on TON). Defaults to a built-in list. | +| `tokenSections` | CryptoOnrampTokenSectionConfig[] | Optional section configs grouping `tokens` in the picker. | +| `paymentMethods` | CryptoPaymentMethod[] | Source crypto payment methods (what the user pays with on another chain). Defaults to a built-in list. | +| `methodSections` | PaymentMethodSectionConfig[] | Optional section configs grouping `paymentMethods` in the picker. | +| `chains` | Record<string, ChainInfo> | Custom CAIP-2 → chain display info overrides. Merged on top of the built-in defaults, so consumers only need to provide what they want to override or add — for example, a single entry keyed by `'eip155:42161'` with a `name` of `'Arbitrum'` and a `logo` URL. | +| `defaultTokenId` | `string` | ID of the target token pre-selected on mount. | +| `defaultMethodId` | `string` | ID of the source payment method pre-selected on mount. | + +#### CryptoOnrampToken + +Target token (what the user is buying on TON) in the crypto onramp widget. Kept separate from `AppkitUIToken` because `address` is the raw form expected by the onramp provider (e.g. `"0x0000000000000000000000000000000000000000"` for native TON, `"EQCx..."` for USDT jetton master). + +| Field | Type | Description | +| --- | --- | --- | +| `id`\* | `string` | Stable identifier used by section configs and pre-selection props. | +| `symbol`\* | `string` | Token symbol, e.g. `"TON"`, `"USDT"`. | +| `name`\* | `string` | Full token name, e.g. `"Toncoin"`, `"Tether"`. | +| `decimals`\* | `number` | Number of decimals for the token. | +| `address`\* | `string` | Address as the onramp provider expects it. | +| `logo` | `string` | Optional logo URL. | + +#### CryptoOnrampTokenSectionConfig + +Section configuration grouping [`CryptoOnrampToken`](#cryptoonramptoken) entries by id in a picker. + +| Field | Type | Description | +| --- | --- | --- | +| `title`\* | `string` | Section header (typically already localized by the caller). | +| `ids`\* | `string[]` | Ids of [`CryptoOnrampToken`](#cryptoonramptoken) entries to include in this section, in order. | + +#### CryptoOnrampWidgetProps + +Props for [`CryptoOnrampWidget`](#cryptoonrampwidget) — extends [`CryptoOnrampProviderProps`](#cryptoonrampproviderprops) (tokens, payment methods, defaults, chain overrides) plus the native `
          ` props the widget root forwards. + +| Field | Type | Description | +| --- | --- | --- | +| `children` | (props: CryptoOnrampWidgetRenderProps) => ReactNode | Custom render function. When provided, replaces the default [`CryptoOnrampWidgetUI`](#cryptoonrampwidgetui) and is called with the full [`CryptoOnrampWidgetRenderProps`](#cryptoonrampwidgetrenderprops) (context state, actions and forwarded `
          ` props), so callers can build a fully custom UI on top of the same provider. | +| `tokens` | CryptoOnrampToken[] | Target tokens (what the user buys on TON). Defaults to a built-in list. | +| `tokenSections` | CryptoOnrampTokenSectionConfig[] | Optional section configs grouping `tokens` in the picker. | +| `paymentMethods` | CryptoPaymentMethod[] | Source crypto payment methods (what the user pays with on another chain). Defaults to a built-in list. | +| `methodSections` | PaymentMethodSectionConfig[] | Optional section configs grouping `paymentMethods` in the picker. | +| `chains` | Record<string, ChainInfo> | Custom CAIP-2 → chain display info overrides. Merged on top of the built-in defaults, so consumers only need to provide what they want to override or add — for example, a single entry keyed by `'eip155:42161'` with a `name` of `'Arbitrum'` and a `logo` URL. | +| `defaultTokenId` | `string` | ID of the target token pre-selected on mount. | +| `defaultMethodId` | `string` | ID of the source payment method pre-selected on mount. | + +#### CryptoOnrampWidgetRenderProps + +Props for [`CryptoOnrampWidgetUI`](#cryptoonrampwidgetui) (and for the custom render callback on [`CryptoOnrampWidget`](#cryptoonrampwidget)) — the full [`CryptoOnrampContextType`](#cryptoonrampcontexttype) state and actions, plus the native `
          ` props the widget root forwards (`className`, `style`, etc.). + +| Field | Type | Description | +| --- | --- | --- | +| `tokens`\* | CryptoOnrampToken[] | Full list of target tokens the user can buy. | +| `tokenSections` | CryptoOnrampTokenSectionConfig[] | Optional section configs grouping `tokens` in the picker. | +| `selectedToken`\* | CryptoOnrampToken \| null | Currently selected target token to buy. `null` until tokens load. | +| `setSelectedToken`\* | (token: CryptoOnrampToken) => void | Updates `selectedToken`. | +| `paymentMethods`\* | CryptoPaymentMethod[] | Available source crypto payment methods. | +| `methodSections` | PaymentMethodSectionConfig[] | Optional section configs grouping `paymentMethods` in the picker. | +| `selectedMethod`\* | CryptoPaymentMethod | Currently selected source payment method. | +| `setSelectedMethod`\* | (method: CryptoPaymentMethod) => void | Updates `selectedMethod`. | +| `chains`\* | Record<string, ChainInfo> | CAIP-2 → chain display info map (built-in defaults merged with consumer overrides). | +| `amount`\* | `string` | Current amount input value as a decimal string. | +| `setAmount`\* | `(value: string) => void` | Updates `amount`. | +| `amountInputMode`\* | CryptoAmountInputMode | Which side `amount` is denominated in — see [`CryptoAmountInputMode`](#cryptoamountinputmode). | +| `setAmountInputMode`\* | (mode: CryptoAmountInputMode) => void | Updates `amountInputMode`. | +| `convertedAmount`\* | `string` | Other side of `amount` after applying the current quote's rate. | +| `presetAmounts`\* | OnrampAmountPreset[] | Quick-pick amount buttons rendered in the widget. | +| `quote`\* | CryptoOnrampQuote \| null | Current quote, or `null` if not yet fetched / invalidated. | +| `isLoadingQuote`\* | `boolean` | Whether a quote is in flight (includes the input-debounce window). | +| `quoteError`\* | `string \| null` | Quote-side validation/fetch error as an i18n key, or `null`. | +| `quoteProviderName`\* | `string \| null` | Display name of the provider behind the current quote, when available. | +| `deposit`\* | CryptoOnrampDeposit \| null | Current deposit returned by the provider once `createDeposit` succeeded. | +| `isCreatingDeposit`\* | `boolean` | Whether `createDeposit` is in flight. | +| `depositError`\* | `string \| null` | Deposit-side error as an i18n key, or `null`. | +| `depositAmount`\* | `string` | Formatted deposit amount the user must send on the source chain. | +| `createDeposit`\* | `() => void` | Triggers deposit creation from the current quote. | +| `depositStatus`\* | CryptoOnrampStatus \| null | Latest deposit status polled via [`useCryptoOnrampStatus`](#usecryptoonrampstatus), or `null`. | +| `isRefundAddressRequired`\* | `boolean` | Whether the current quote provider requires a refund address before deposit. | +| `isReversedAmountSupported`\* | `boolean` | Whether the current quote provider supports reversed (target-amount) input. | +| `refundAddress`\* | `string` | Refund address the user typed, if `isRefundAddressRequired`. | +| `setRefundAddress`\* | `(address: string) => void` | Updates `refundAddress`. | +| `targetBalance`\* | `string` | Connected wallet's balance of the selected target token (formatted, token units). | +| `isLoadingTargetBalance`\* | `boolean` | Whether the target token balance is being fetched. | +| `isWalletConnected`\* | `boolean` | Whether a TON wallet is currently connected. | +| `canContinue`\* | `boolean` | Whether the user can proceed — valid amount, quote available, and wallet connected. | +| `onReset`\* | `() => void` | Invalidates the active quote and clears the deposit, returning the widget to its initial state. | + +#### CryptoPaymentMethod + +Source crypto payment method (what the user pays with on another chain) in the crypto onramp widget. + +| Field | Type | Description | +| --- | --- | --- | +| `id`\* | `string` | Stable identifier for the method — used for selection state and `methodSections.ids` | +| `symbol`\* | `string` | Token symbol, e.g. "USDC", "USDT". | +| `name`\* | `string` | Full token name shown in the picker, e.g. "USD Coin", "Tether". | +| `chain`\* | `string` | Source chain in CAIP-2 format, e.g. "eip155:8453", "eip155:56" — passed as `sourceChain` to the onramp provider. The widget resolves a display name and logo for it via the `chains` map (see `CryptoOnrampWidgetProvider`). | +| `decimals`\* | `number` | Number of decimals for the token (used to convert between display and base units) | +| `address`\* | `string` | Token contract address on the source network (empty string / zero address for native) | +| `logo` | `string` | Token logo URL shown in the picker and selectors. | + +#### OnrampAmountPreset + +Quick-pick amount button shown above the crypto-onramp input (carried on [`CryptoOnrampContextType`](#cryptoonrampcontexttype)'s `presetAmounts`). + +| Field | Type | Description | +| --- | --- | --- | +| `amount`\* | `string` | Amount value the preset sets on click (decimal string). | +| `label`\* | `string` | Button label shown to the user. | + +#### PaymentMethodSectionConfig + +Section configuration grouping [`CryptoPaymentMethod`](#cryptopaymentmethod) entries by id in a picker. + +| Field | Type | Description | +| --- | --- | --- | +| `title`\* | `string` | Section header (typically already localized by the caller). | +| `ids`\* | `string[]` | Ids of [`CryptoPaymentMethod`](#cryptopaymentmethod) entries to include in this section, in order. | + +#### UseCreateCryptoOnrampDepositParameters + +Parameters accepted by [`useCreateCryptoOnrampDeposit`](#usecreatecryptoonrampdeposit) — TanStack Query mutation options forwarded via `parameters.mutation`. + +```ts +type UseCreateCryptoOnrampDepositParameters = CreateCryptoOnrampDepositMutationOptions; +``` + +#### UseCreateCryptoOnrampDepositReturnType + +Return type of [`useCreateCryptoOnrampDeposit`](#usecreatecryptoonrampdeposit) — TanStack Query mutation result. + +```ts +type UseCreateCryptoOnrampDepositReturnType = UseMutationResult< + CreateCryptoOnrampDepositData, + CreateCryptoOnrampDepositErrorType, + CreateCryptoOnrampDepositVariables, + context +>; +``` + +#### UseCryptoOnrampProviderParameters + +Parameters accepted by [`useCryptoOnrampProvider`](#usecryptoonrampprovider) — optional provider id forwarded to [`getCryptoOnrampProvider`](/ecosystem/appkit/reference/appkit#getcryptoonrampprovider). + +```ts +type UseCryptoOnrampProviderParameters = GetCryptoOnrampProviderOptions; +``` + +#### UseCryptoOnrampProviderReturnType + +Return type of [`useCryptoOnrampProvider`](#usecryptoonrampprovider) — the matching [`CryptoOnrampProviderInterface`](/ecosystem/appkit/reference/appkit#cryptoonrampproviderinterface), or `undefined` when none is registered (the hook swallows the throw from [`getCryptoOnrampProvider`](/ecosystem/appkit/reference/appkit#getcryptoonrampprovider)). + +```ts +type UseCryptoOnrampProviderReturnType = GetCryptoOnrampProviderReturnType | undefined; +``` + +#### UseCryptoOnrampProvidersReturnType + +Return type of [`useCryptoOnrampProviders`](#usecryptoonrampproviders) — array of every [`CryptoOnrampProviderInterface`](/ecosystem/appkit/reference/appkit#cryptoonrampproviderinterface) currently registered on the AppKit instance. + +```ts +type UseCryptoOnrampProvidersReturnType = GetCryptoOnrampProvidersReturnType; +``` + +#### UseCryptoOnrampQuoteParameters + +Parameters accepted by [`useCryptoOnrampQuote`](#usecryptoonrampquote) — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the source/target assets, amount and optional provider override forwarded to [`getCryptoOnrampQuote`](/ecosystem/appkit/reference/appkit#getcryptoonrampquote). + +| Field | Type | Description | +| --- | --- | --- | +| `amount` | `string` | Amount to onramp (either source or target crypto, depending on isSourceAmount) | +| `sourceCurrencyAddress` | `string` | Source crypto currency address (contract address or 0x0... for native) | +| `sourceChain` | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | +| `targetCurrencyAddress` | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | +| `recipientAddress` | `string` | TON address that will receive the target crypto | +| `refundAddress` | `string` | Refund address for the source crypto | +| `isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerId` | `string` | Provider to quote against. Defaults to the registered default provider. | +| `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +#### UseCryptoOnrampQuoteReturnType + +Return type of [`useCryptoOnrampQuote`](#usecryptoonrampquote) — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + +```ts +type UseCryptoOnrampQuoteReturnType = UseQueryReturnType< + selectData, + GetCryptoOnrampQuoteErrorType +>; +``` + +#### UseCryptoOnrampStatusParameters + +Parameters accepted by [`useCryptoOnrampStatus`](#usecryptoonrampstatus) — TanStack Query options (`select`, `enabled`, `refetchInterval`, …) plus the deposit id, originating provider id and optional provider override forwarded to [`getCryptoOnrampStatus`](/ecosystem/appkit/reference/appkit#getcryptoonrampstatus). + +| Field | Type | Description | +| --- | --- | --- | +| `depositId` | `string` | Deposit id | +| `providerId` | `string` | Identifier of the provider that issued this deposit | +| `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +#### UseCryptoOnrampStatusReturnType + +Return type of [`useCryptoOnrampStatus`](#usecryptoonrampstatus) — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + +```ts +type UseCryptoOnrampStatusReturnType = UseQueryReturnType< + selectData, + GetCryptoOnrampStatusErrorType +>; +``` + +### Jettons + +#### UseJettonBalanceByAddressParameters + +Parameters accepted by [`useJettonBalanceByAddress`](#usejettonbalancebyaddress) — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the jetton master, owner address, decimals and optional network override. + +| Field | Type | Description | +| --- | --- | --- | +| `jettonAddress` | UserFriendlyAddress | Jetton master contract address (the token, not the user's wallet for it). | +| `ownerAddress` | UserFriendlyAddress | Owner of the jetton wallet — typically the connected user's address. | +| `jettonDecimals` | `number` | Decimals declared by the jetton master. Used to format the raw balance into a human-readable string. | +| `network` | Network | Network to read the balance from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +#### UseJettonBalanceByAddressReturnType + +Return type of [`useJettonBalanceByAddress`](#usejettonbalancebyaddress) — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + +```ts +type UseJettonBalanceByAddressReturnType = UseQueryReturnType< + selectData, + GetJettonBalanceErrorType +>; +``` + +#### UseJettonInfoParameters + +Parameters accepted by [`useJettonInfo`](#usejettoninfo) — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the jetton master address and optional network override. + +| Field | Type | Description | +| --- | --- | --- | +| `address` | UserFriendlyAddress | Jetton master contract address whose metadata is being fetched. | +| `network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +#### UseJettonInfoReturnType + +Return type of [`useJettonInfo`](#usejettoninfo) — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. `data` is `null` when the indexer has no record for that master address. + +```ts +type UseJettonInfoReturnType = UseQueryReturnType< + selectData, + GetJettonInfoErrorType +>; +``` + +#### UseJettonWalletAddressParameters + +Parameters accepted by [`useJettonWalletAddress`](#usejettonwalletaddress) — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the jetton master, owner address and optional network override. + +| Field | Type | Description | +| --- | --- | --- | +| `jettonAddress` | UserFriendlyAddress | Jetton master contract address. | +| `ownerAddress` | UserFriendlyAddress | Owner whose jetton wallet should be derived. | +| `network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +#### UseJettonWalletAddressReturnType + +Return type of [`useJettonWalletAddress`](#usejettonwalletaddress) — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + +```ts +type UseJettonWalletAddressReturnType = UseQueryReturnType< + selectData, + GetJettonWalletAddressErrorType +>; +``` + +#### UseJettonsByAddressParameters + +Parameters accepted by [`useJettonsByAddress`](#usejettonsbyaddress) — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the owner address, optional network override and pagination. + +| Field | Type | Description | +| --- | --- | --- | +| `address` | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `network` | Network | Network to read the jettons from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `limit` | `number` | Maximum number of jettons to return. | +| `offset` | `number` | Number of jettons to skip before returning results — used for pagination. | +| `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +#### UseJettonsByAddressReturnType + +Return type of [`useJettonsByAddress`](#usejettonsbyaddress) — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + +```ts +type UseJettonsByAddressReturnType = UseQueryReturnType< + selectData, + GetJettonsErrorType +>; +``` + +#### UseJettonsParameters + +Parameters accepted by [`useJettons`](#usejettons) — same shape as [`UseJettonsByAddressParameters`](#usejettonsbyaddressparameters). The hook resolves `address` from the selected wallet and overrides any value supplied here. + +| Field | Type | Description | +| --- | --- | --- | +| `address` | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](/ecosystem/appkit/reference/appkit#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `network` | Network | Network to read the jettons from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `limit` | `number` | Maximum number of jettons to return. | +| `offset` | `number` | Number of jettons to skip before returning results — used for pagination. | +| `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | + +#### UseJettonsReturnType + +Return type of [`useJettons`](#usejettons) — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + +```ts +type UseJettonsReturnType = UseJettonsByAddressReturnType; +``` + +#### UseTransferJettonParameters + +Parameters accepted by [`useTransferJetton`](#usetransferjetton) — TanStack Query mutation options. + +```ts +type UseTransferJettonParameters = TransferJettonOptions; +``` + +#### UseTransferJettonReturnType + +Return type of [`useTransferJetton`](#usetransferjetton) — TanStack Query mutation result. + +```ts +type UseTransferJettonReturnType = UseMutationReturnType< + TransferJettonData, + TransferJettonErrorType, + TransferJettonVariables, + context, + ( + variables: TransferJettonVariables, + options?: MutateOptions, + ) => void, + MutateFunction +>; +``` + +#### UseWatchJettonsByAddressParameters + +Parameters accepted by [`useWatchJettonsByAddress`](#usewatchjettonsbyaddress) — same fields as [`WatchJettonsByAddressOptions`](/ecosystem/appkit/reference/appkit#watchjettonsbyaddressoptions), all optional so callers can render the hook before the address is known. + +```ts +type UseWatchJettonsByAddressParameters = Partial; +``` + +#### UseWatchJettonsParameters + +Parameters accepted by [`useWatchJettons`](#usewatchjettons) — update callback and optional network override. The hook resolves the address from the selected wallet. + +```ts +type UseWatchJettonsParameters = Partial; +``` + +### NFTs + +#### NftItemProps + +Props accepted by [`NftItem`](#nftitem) — extends the native `
          ); +/** + * Props accepted by {@link Input.Slot}. + * + * @public + * @category Type + * @section UI + */ export interface InputSlotProps extends ComponentProps<'div'> { + /** Which edge of the field the slot adheres to. */ side?: 'left' | 'right'; } @@ -117,6 +155,13 @@ const Slot: FC = ({ side, className, children, ...props }) => (
          ); +/** + * Props accepted by {@link Input.Input} — standard `` props. Size, disabled, loading, and resizable behavior are inherited from the surrounding {@link Input.Container}. + * + * @public + * @category Type + * @section UI + */ export type InputControlProps = ComponentProps<'input'>; const InputControl: FC = ({ className, disabled: propsDisabled, onChange, ...props }) => { @@ -183,12 +228,28 @@ const Caption: FC> = ({ className, children, ...props }) ); }; +/** + * Compound text-input component. Use the default export as the outer wrapper (it is the {@link Input.Container}) and compose sub-components for the header, field, slots, control, and caption. State flags (`disabled`, `error`, `loading`, `resizable`, `size`) live on the container and are read by the inner control via context. + * + * @sample docs/examples/src/appkit/components/ui#INPUT + * + * @public + * @category Component + * @section UI + */ export const Input = Object.assign(Container, { + /** Outer wrapper that provides input context (size, variant, disabled, error, loading, resizable). */ Container, + /** Header row above the field — holds the title and optional trailing controls. */ Header, + /** Title text shown inside {@link Input.Header}. */ Title, + /** Horizontal row that holds slots and the input control. */ Field, + /** Side-anchored slot used for adornments such as icons or buttons. */ Slot, + /** The actual `` control. Respects context flags and reads its size/variant from {@link Input.Container}. */ Input: InputControl, + /** Caption / helper text below the field. Switches to error styling when the container has `error` set. */ Caption, }); diff --git a/packages/appkit-react/src/components/ui/logo-with-network/logo-with-network.tsx b/packages/appkit-react/src/components/ui/logo-with-network/logo-with-network.tsx index c62f53c74..c3d4e06c2 100644 --- a/packages/appkit-react/src/components/ui/logo-with-network/logo-with-network.tsx +++ b/packages/appkit-react/src/components/ui/logo-with-network/logo-with-network.tsx @@ -13,21 +13,37 @@ import clsx from 'clsx'; import { Logo } from '../logo'; import styles from './logo-with-network.module.css'; +/** + * Props accepted by {@link LogoWithNetwork}. + * + * @public + * @category Type + * @section UI + */ export interface LogoWithNetworkProps extends ComponentPropsWithoutRef<'span'> { - /** Size of the main logo in pixels */ + /** Size of the main logo in pixels. Defaults to `30`. The network badge is sized to `size * 0.4`. */ size?: number; - /** Image source for the main logo */ + /** Image source for the main logo. */ src?: string; - /** Alt text for the main logo */ + /** Alt text for the main logo. */ alt?: string; - /** Fallback text for the main logo */ + /** Fallback text shown when the main logo image fails or is missing. */ fallback?: string; - /** Image source for the network badge */ + /** Image source for the network badge overlay. When omitted, the badge is not rendered. */ networkSrc?: string; - /** Alt text for the network badge */ + /** Alt text for the network badge. */ networkAlt?: string; } +/** + * Token logo with an overlaid network badge — wraps {@link Logo} and renders a smaller secondary logo as a corner badge to indicate which network the asset belongs to. + * + * @sample docs/examples/src/appkit/components/ui#LOGO_WITH_NETWORK + * + * @public + * @category Component + * @section UI + */ export const LogoWithNetwork = forwardRef, LogoWithNetworkProps>( ({ size = 30, src, alt, fallback, networkSrc, networkAlt, className, ...props }, ref) => { return ( diff --git a/packages/appkit-react/src/components/ui/logo/logo.tsx b/packages/appkit-react/src/components/ui/logo/logo.tsx index 1a2bf3c04..7dbee70f8 100644 --- a/packages/appkit-react/src/components/ui/logo/logo.tsx +++ b/packages/appkit-react/src/components/ui/logo/logo.tsx @@ -86,13 +86,33 @@ const LogoFallback = forwardRef, LogoFallbackProps>(({ dela LogoFallback.displayName = 'LogoFallback'; +/** + * Props accepted by {@link Logo}. + * + * @public + * @category Type + * @section UI + */ export interface LogoProps extends ComponentPropsWithoutRef<'span'> { + /** Square size in pixels for the rendered logo. Defaults to `30`. */ size?: number; + /** Image URL to render. While loading or on failure, the fallback is shown. */ src?: string; + /** Alt text passed to the underlying ``. When `fallback` is not provided, its first character is shown as the fallback. If both are missing, no fallback is rendered. */ alt?: string; + /** Text shown in place of the image when `src` fails or is missing (defaults to the first character of `alt`). */ fallback?: string; } +/** + * Square logo / avatar primitive — renders an `` when `src` loads successfully, otherwise shows a text fallback (after a brief delay to avoid flicker). Useful for token icons, wallet avatars, and project logos. + * + * @sample docs/examples/src/appkit/components/ui#LOGO + * + * @public + * @category Component + * @section UI + */ export const Logo = forwardRef, LogoProps>(({ size = 30, src, alt, fallback, ...props }, ref) => { return ( void; - /** - * Modal title. - */ + /** Optional title rendered in the modal header. */ title?: string; - /** - * Modal content. - */ + /** Modal body content. */ children?: ReactNode; - /** - * Additional class name for the content container. - */ + /** Additional class name applied to the content container. */ className?: string; - /** - * Additional class name for the body container. - */ + /** Additional class name applied to the body container. */ bodyClassName?: string; } +/** + * Centered modal dialog with a header (optional title + close button) and a scrollable body. Clicking the overlay closes the modal. Clicks on the content do not bubble through. + * + * @sample docs/examples/src/appkit/components/ui#MODAL + * + * @public + * @category Component + * @section UI + */ export const Modal: FC = ({ open, onOpenChange, title, children, className, bodyClassName }) => { return ( diff --git a/packages/appkit-react/src/components/ui/select/select.tsx b/packages/appkit-react/src/components/ui/select/select.tsx index 46258752f..ea406356b 100644 --- a/packages/appkit-react/src/components/ui/select/select.tsx +++ b/packages/appkit-react/src/components/ui/select/select.tsx @@ -16,6 +16,13 @@ import type { ButtonProps } from '../button'; import styles from './select.module.css'; import { SelectContext, useSelectContext } from './use-select-context'; +/** + * Props accepted by {@link Select.Root}. + * + * @public + * @category Type + * @section UI + */ export interface SelectRootProps { /** Controlled selected value. */ value?: string; @@ -31,6 +38,7 @@ export interface SelectRootProps { onOpenChange?: (open: boolean) => void; /** When true, the trigger is non-interactive. */ disabled?: boolean; + /** Compound sub-components — {@link Select.Trigger}, {@link Select.Content}, {@link Select.Item}. */ children: ReactNode; } @@ -87,6 +95,13 @@ const SelectRoot: FC = ({ return {children}; }; +/** + * Props accepted by {@link Select.Trigger} — same as {@link ButtonProps}. The trigger inherits `disabled` from the surrounding root if set. + * + * @public + * @category Type + * @section UI + */ export type SelectTriggerProps = ButtonProps; const SelectTrigger = forwardRef, SelectTriggerProps>( @@ -125,6 +140,13 @@ const SelectTrigger = forwardRef, SelectTriggerProps>( SelectTrigger.displayName = 'SelectTrigger'; +/** + * Props accepted by {@link Select.Content}. + * + * @public + * @category Type + * @section UI + */ export interface SelectContentProps extends ComponentPropsWithoutRef<'div'> { /** Horizontal alignment relative to the trigger. */ align?: 'start' | 'end'; @@ -230,8 +252,17 @@ const SelectContent: FC = ({ ); }; +/** + * Props accepted by {@link Select.Item}. + * + * @public + * @category Type + * @section UI + */ export interface SelectItemProps extends ComponentPropsWithoutRef<'div'> { + /** Value committed to {@link Select.Root} when this item is chosen. */ value: string; + /** When true, the item is not selectable and is excluded from keyboard navigation. */ disabled?: boolean; } @@ -266,9 +297,22 @@ const SelectItem = forwardRef, SelectItemProps>( SelectItem.displayName = 'SelectItem'; +/** + * Compound select / dropdown component with controlled or uncontrolled state. The content is portaled to `document.body` and positioned relative to the trigger. Closes on outside click, `Escape`, or item selection. + * + * @sample docs/examples/src/appkit/components/ui#SELECT + * + * @public + * @category Component + * @section UI + */ export const Select = { + /** Provider that owns the selected value and open state, controlled or uncontrolled. */ Root: SelectRoot, + /** {@link Button}-based trigger that toggles the popover and exposes `aria-expanded`. */ Trigger: SelectTrigger, + /** Portaled popover that renders the list of items. Positioned under the trigger with optional `sideOffset`. */ Content: SelectContent, + /** Selectable option row. Commits its `value` to the root on click. */ Item: SelectItem, }; diff --git a/packages/appkit-react/src/components/ui/skeleton/skeleton.tsx b/packages/appkit-react/src/components/ui/skeleton/skeleton.tsx index 7a27f5926..d924b8be2 100644 --- a/packages/appkit-react/src/components/ui/skeleton/skeleton.tsx +++ b/packages/appkit-react/src/components/ui/skeleton/skeleton.tsx @@ -12,11 +12,29 @@ import clsx from 'clsx'; import styles from './skeleton.module.css'; +/** + * Props accepted by {@link Skeleton}. + * + * @public + * @category Type + * @section UI + */ export interface SkeletonProps extends ComponentProps<'div'> { + /** Width of the placeholder. Accepts any valid CSS length or a number (interpreted as pixels). */ width?: string | number; + /** Height of the placeholder. Accepts any valid CSS length or a number (interpreted as pixels). */ height?: string | number; } +/** + * Animated placeholder block used while data is loading. Supply `width` / `height` to match the dimensions of the eventual content. + * + * @sample docs/examples/src/appkit/components/ui#SKELETON + * + * @public + * @category Component + * @section UI + */ export const Skeleton = forwardRef( ({ className, width, height, style, ...props }, ref) => { return ( diff --git a/packages/appkit-react/src/components/ui/tabs/tabs.tsx b/packages/appkit-react/src/components/ui/tabs/tabs.tsx index ebe89d887..25d52278b 100644 --- a/packages/appkit-react/src/components/ui/tabs/tabs.tsx +++ b/packages/appkit-react/src/components/ui/tabs/tabs.tsx @@ -22,13 +22,33 @@ const TabsContext = createContext({ onValueChange: () => {}, }); +/** + * Props accepted by {@link Tabs}. + * + * @public + * @category Type + * @section UI + */ export interface TabsProps extends ComponentProps<'div'> { + /** Controlled active tab value. */ value?: string; + /** Initial active tab when uncontrolled. Defaults to `''`. */ defaultValue?: string; + /** Called whenever the active tab changes. */ onValueChange?: (value: string) => void; + /** Compound sub-components — typically {@link TabsList} (with {@link TabsTrigger}s) followed by {@link TabsContent}s. */ children: ReactNode; } +/** + * Root tabs container — owns the active value (controlled or uncontrolled) and shares it with descendant {@link TabsList}, {@link TabsTrigger}, and {@link TabsContent} via context. + * + * @sample docs/examples/src/appkit/components/ui#TABS + * + * @public + * @category Component + * @section UI + */ export const Tabs: FC = ({ value: controlledValue, defaultValue = '', @@ -61,10 +81,25 @@ export const Tabs: FC = ({ ); }; +/** + * Props accepted by {@link TabsList}. + * + * @public + * @category Type + * @section UI + */ export interface TabsListProps extends ComponentProps<'div'> { + /** Tab triggers — typically one or more {@link TabsTrigger}s. */ children: ReactNode; } +/** + * Horizontal list of tab triggers with `role="tablist"`. + * + * @public + * @category Component + * @section UI + */ export const TabsList: FC = ({ children, className, ...props }) => { return (
          @@ -73,11 +108,27 @@ export const TabsList: FC = ({ children, className, ...props }) = ); }; +/** + * Props accepted by {@link TabsTrigger}. + * + * @public + * @category Type + * @section UI + */ export interface TabsTriggerProps extends ComponentProps<'button'> { + /** Value committed to the parent {@link Tabs} when this trigger is activated. */ value: string; + /** Trigger label / content. */ children: ReactNode; } +/** + * Tab trigger button with `role="tab"`. Activates its `value` on click and reflects active state via `aria-selected` and `data-state`. + * + * @public + * @category Component + * @section UI + */ export const TabsTrigger: FC = ({ value, children, className, ...props }) => { const ctx = useContext(TabsContext); const isActive = ctx.value === value; @@ -97,11 +148,27 @@ export const TabsTrigger: FC = ({ value, children, className, ); }; +/** + * Props accepted by {@link TabsContent}. + * + * @public + * @category Type + * @section UI + */ export interface TabsContentProps extends ComponentProps<'div'> { + /** Value this panel is associated with — rendered only when the parent {@link Tabs} is on this value. */ value: string; + /** Panel content. */ children: ReactNode; } +/** + * Tab panel rendered with `role="tabpanel"`. Returns `null` unless its `value` matches the active {@link Tabs} value. + * + * @public + * @category Component + * @section UI + */ export const TabsContent: FC = ({ value, children, className, ...props }) => { const ctx = useContext(TabsContext); const isActive = ctx.value === value; diff --git a/packages/appkit-react/src/features/balances/components/send-jetton-button/send-jetton-button.tsx b/packages/appkit-react/src/features/balances/components/send-jetton-button/send-jetton-button.tsx index 78048a8ef..fe2bf1680 100644 --- a/packages/appkit-react/src/features/balances/components/send-jetton-button/send-jetton-button.tsx +++ b/packages/appkit-react/src/features/balances/components/send-jetton-button/send-jetton-button.tsx @@ -14,17 +14,37 @@ import { useI18n, useAppKit } from '../../../settings'; import type { SendProps } from '../../../transaction'; import { Send } from '../../../transaction'; +/** + * Props accepted by {@link SendJettonButton} — extends the base `Send` button props (button text, sizing, callbacks) with the jetton-transfer details. + * + * @public + * @category Type + * @section Balances + */ export interface SendJettonButtonProps extends Omit { + /** Recipient address. */ recipientAddress: string; + /** Amount in jetton units as a human-readable decimal string. Converted to raw smallest units via `jetton.decimals`. */ amount: string; + /** Jetton master metadata — `address` (master contract), `symbol` (rendered in the button label) and `decimals` (used to format `amount`). */ jetton: { address: string; symbol: string; decimals: number; }; + /** Optional human-readable comment attached to the transfer. */ comment?: string; } +/** + * Pre-wired button that builds a jetton transfer with {@link appkit:createTransferJettonTransaction} and dispatches it through the standard `Send` flow on click — disabled until `recipientAddress`, `amount`, `jetton.address` and `jetton.decimals` are all set. Throws inside the click handler when `jetton.address` or `jetton.decimals` is missing. + * + * @sample docs/examples/src/appkit/components/balances#SEND_JETTON_BUTTON + * + * @public + * @category Component + * @section Balances + */ export const SendJettonButton: FC = ({ recipientAddress, amount, diff --git a/packages/appkit-react/src/features/balances/components/send-ton-button/send-ton-button.tsx b/packages/appkit-react/src/features/balances/components/send-ton-button/send-ton-button.tsx index 30201ae49..633223eb1 100644 --- a/packages/appkit-react/src/features/balances/components/send-ton-button/send-ton-button.tsx +++ b/packages/appkit-react/src/features/balances/components/send-ton-button/send-ton-button.tsx @@ -14,12 +14,31 @@ import { useI18n, useAppKit } from '../../../settings'; import type { SendProps } from '../../../transaction'; import { Send } from '../../../transaction'; +/** + * Props accepted by {@link SendTonButton} — extends the base `Send` button props (button text, sizing, callbacks) with the TON-transfer details. + * + * @public + * @category Type + * @section Balances + */ export interface SendTonButtonProps extends Omit { + /** Recipient address. */ recipientAddress: string; + /** Amount in TON as a human-readable decimal string (e.g., `"1.5"`). Converted to nano-TON internally. */ amount: string; + /** Optional human-readable comment attached to the transfer. */ comment?: string; } +/** + * Pre-wired button that builds a TON transfer with {@link appkit:createTransferTonTransaction} and dispatches it through the standard `Send` flow on click — disabled until both `recipientAddress` and `amount` are set. + * + * @sample docs/examples/src/appkit/components/balances#SEND_TON_BUTTON + * + * @public + * @category Component + * @section Balances + */ export const SendTonButton: FC = ({ recipientAddress, amount, comment, ...props }) => { const appKit = useAppKit(); const { t } = useI18n(); diff --git a/packages/appkit-react/src/features/balances/hooks/use-balance-by-address.ts b/packages/appkit-react/src/features/balances/hooks/use-balance-by-address.ts index e43423235..c17a40545 100644 --- a/packages/appkit-react/src/features/balances/hooks/use-balance-by-address.ts +++ b/packages/appkit-react/src/features/balances/hooks/use-balance-by-address.ts @@ -14,16 +14,40 @@ import { useQuery } from '../../../libs/query'; import type { UseQueryReturnType } from '../../../libs/query'; import { useNetwork } from '../../network'; +/** + * Parameters accepted by {@link useBalanceByAddress} — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the target address and optional network override. + * + * @public + * @category Type + * @section Balances + */ export type UseBalanceByAddressParameters = GetBalanceByAddressQueryConfig; +/** + * Return type of {@link useBalanceByAddress} — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + * + * @public + * @category Type + * @section Balances + */ export type UseBalanceByAddressReturnType = UseQueryReturnType< selectData, GetBalanceErrorType >; /** - * Hook to get balance + * React hook reading the Toncoin balance of an arbitrary address through TanStack Query — useful for addresses that aren't tied to the selected wallet (use {@link useBalance} for the selected wallet). + * + * @param parameters - {@link UseBalanceByAddressParameters} Target address, optional network override, and TanStack Query overrides. + * @expand parameters + * @returns TanStack Query result for the balance read. + * + * @sample docs/examples/src/appkit/hooks/balances#USE_BALANCE_BY_ADDRESS + * + * @public + * @category Hook + * @section Balances */ export const useBalanceByAddress = ( parameters: UseBalanceByAddressParameters = {}, diff --git a/packages/appkit-react/src/features/balances/hooks/use-balance.ts b/packages/appkit-react/src/features/balances/hooks/use-balance.ts index b4d6a1dd6..930c98f54 100644 --- a/packages/appkit-react/src/features/balances/hooks/use-balance.ts +++ b/packages/appkit-react/src/features/balances/hooks/use-balance.ts @@ -12,12 +12,36 @@ import { useAddress } from '../../wallets/hooks/use-address'; import { useBalanceByAddress } from './use-balance-by-address'; import type { UseBalanceByAddressParameters, UseBalanceByAddressReturnType } from './use-balance-by-address'; +/** + * Parameters accepted by {@link useBalance} — same shape as {@link UseBalanceByAddressParameters}. The hook resolves `address` from the selected wallet and overrides any value supplied here. + * + * @public + * @category Type + * @section Balances + */ export type UseBalanceParameters = UseBalanceByAddressParameters; +/** + * Return type of {@link useBalance} — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + * + * @public + * @category Type + * @section Balances + */ export type UseBalanceReturnType = UseBalanceByAddressReturnType; /** - * Hook to get balance of the selected wallet + * React hook reading the Toncoin balance of the currently selected wallet through TanStack Query — auto-resolves the wallet address (use {@link useBalanceByAddress} for an arbitrary address). + * + * @param parameters - {@link UseBalanceParameters} TanStack Query overrides (`select`, `enabled`, `staleTime`, …) and an optional network override. + * @expand parameters + * @returns TanStack Query result for the balance read. + * + * @sample docs/examples/src/appkit/hooks/balances#USE_BALANCE + * + * @public + * @category Hook + * @section Balances */ export const useBalance = ( parameters: UseBalanceParameters = {}, diff --git a/packages/appkit-react/src/features/balances/hooks/use-watch-balance-by-address.ts b/packages/appkit-react/src/features/balances/hooks/use-watch-balance-by-address.ts index d03d8ec42..9600eb78a 100644 --- a/packages/appkit-react/src/features/balances/hooks/use-watch-balance-by-address.ts +++ b/packages/appkit-react/src/features/balances/hooks/use-watch-balance-by-address.ts @@ -14,11 +14,26 @@ import { handleBalanceUpdate } from '@ton/appkit/queries'; import { useAppKit } from '../../settings'; +/** + * Parameters accepted by {@link useWatchBalanceByAddress} — same fields as {@link appkit:WatchBalanceByAddressOptions}, all optional so callers can render the hook before the address is known. + * + * @public + * @category Type + * @section Balances + */ export type UseWatchBalanceByAddressParameters = Partial; /** - * Hook to watch balance of a specific address in real-time. - * Automatically updates the TanStack Query cache for `useBalanceByAddress`. + * Subscribe to Toncoin balance updates for an arbitrary address — updates flow into the TanStack Query cache so {@link useBalanceByAddress} picks up the new data automatically. Requires a streaming provider registered for the network — the hook exits silently with a console warning when none is configured. + * + * @param parameters - {@link UseWatchBalanceByAddressParameters} Address, update callback and optional network override. + * @expand parameters + * + * @sample docs/examples/src/appkit/hooks/balances#USE_WATCH_BALANCE_BY_ADDRESS + * + * @public + * @category Hook + * @section Balances */ export const useWatchBalanceByAddress = (parameters: UseWatchBalanceByAddressParameters): void => { const { address, network, onChange } = parameters; diff --git a/packages/appkit-react/src/features/balances/hooks/use-watch-balance.ts b/packages/appkit-react/src/features/balances/hooks/use-watch-balance.ts index 3c3351316..91f93fc9b 100644 --- a/packages/appkit-react/src/features/balances/hooks/use-watch-balance.ts +++ b/packages/appkit-react/src/features/balances/hooks/use-watch-balance.ts @@ -11,11 +11,26 @@ import { useNetwork } from '../../network/hooks/use-network'; import { useWatchBalanceByAddress } from './use-watch-balance-by-address'; import type { UseWatchBalanceByAddressParameters } from './use-watch-balance-by-address'; +/** + * Parameters accepted by {@link useWatchBalance} — same fields as {@link UseWatchBalanceByAddressParameters} minus `address`, which the hook resolves from the selected wallet. + * + * @public + * @category Type + * @section Balances + */ export type UseWatchBalanceParameters = Omit; /** - * Hook to watch balance of the currently selected wallet in real-time. - * Automatically updates the TanStack Query cache for `useBalance`. + * Subscribe to Toncoin balance updates for the currently selected wallet. Updates flow into the TanStack Query cache so {@link useBalance} picks up the new data automatically (use {@link useWatchBalanceByAddress} for a fixed address). Requires a streaming provider registered for the network — the hook exits silently with a console warning when none is configured. + * + * @param parameters - {@link UseWatchBalanceParameters} Update callback and optional network override. + * @expand parameters + * + * @sample docs/examples/src/appkit/hooks/balances#USE_WATCH_BALANCE + * + * @public + * @category Hook + * @section Balances */ export const useWatchBalance = (parameters: UseWatchBalanceParameters = {}): void => { const address = useAddress(); diff --git a/packages/appkit-react/src/features/jettons/hooks/use-jetton-balance-by-address.ts b/packages/appkit-react/src/features/jettons/hooks/use-jetton-balance-by-address.ts index f779d472a..35bcd1ee1 100644 --- a/packages/appkit-react/src/features/jettons/hooks/use-jetton-balance-by-address.ts +++ b/packages/appkit-react/src/features/jettons/hooks/use-jetton-balance-by-address.ts @@ -18,16 +18,40 @@ import { useQuery } from '../../../libs/query'; import type { UseQueryReturnType } from '../../../libs/query'; import { useNetwork } from '../../network'; +/** + * Parameters accepted by {@link useJettonBalanceByAddress} — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the jetton master, owner address, decimals and optional network override. + * + * @public + * @category Type + * @section Jettons + */ export type UseJettonBalanceByAddressParameters = GetJettonBalanceByAddressQueryConfig; +/** + * Return type of {@link useJettonBalanceByAddress} — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + * + * @public + * @category Type + * @section Jettons + */ export type UseJettonBalanceByAddressReturnType = UseQueryReturnType< selectData, GetJettonBalanceErrorType >; /** - * Hook to get jetton balance + * React hook reading a jetton balance for a given owner through TanStack Query — derives the owner's jetton-wallet address from the master and formats the balance using the supplied decimals. + * + * @param parameters - {@link UseJettonBalanceByAddressParameters} Jetton master, owner address, decimals, optional network override and TanStack Query overrides. + * @expand parameters + * @returns TanStack Query result for the jetton balance read. + * + * @sample docs/examples/src/appkit/hooks/jettons#USE_JETTON_BALANCE_BY_ADDRESS + * + * @public + * @category Hook + * @section Jettons */ export const useJettonBalanceByAddress = ( parameters: UseJettonBalanceByAddressParameters = {}, diff --git a/packages/appkit-react/src/features/jettons/hooks/use-jetton-info.ts b/packages/appkit-react/src/features/jettons/hooks/use-jetton-info.ts index a3fed815b..cc18eb31e 100644 --- a/packages/appkit-react/src/features/jettons/hooks/use-jetton-info.ts +++ b/packages/appkit-react/src/features/jettons/hooks/use-jetton-info.ts @@ -14,15 +14,39 @@ import { useQuery } from '../../../libs/query'; import type { UseQueryReturnType } from '../../../libs/query'; import { useNetwork } from '../../network'; +/** + * Parameters accepted by {@link useJettonInfo} — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the jetton master address and optional network override. + * + * @public + * @category Type + * @section Jettons + */ export type UseJettonInfoParameters = GetJettonInfoQueryConfig; +/** + * Return type of {@link useJettonInfo} — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. `data` is `null` when the indexer has no record for that master address. + * + * @public + * @category Type + * @section Jettons + */ export type UseJettonInfoReturnType = UseQueryReturnType< selectData, GetJettonInfoErrorType >; /** - * Hook to get jetton info by address + * React hook reading jetton-master metadata (name, symbol, decimals, image, description) through TanStack Query. + * + * @param parameters - {@link UseJettonInfoParameters} Jetton master address, optional network override and TanStack Query overrides. + * @expand parameters + * @returns TanStack Query result for the jetton info read. + * + * @sample docs/examples/src/appkit/hooks/jettons#USE_JETTON_INFO + * + * @public + * @category Hook + * @section Jettons */ export const useJettonInfo = ( parameters: UseJettonInfoParameters = {}, diff --git a/packages/appkit-react/src/features/jettons/hooks/use-jetton-wallet-address.ts b/packages/appkit-react/src/features/jettons/hooks/use-jetton-wallet-address.ts index 7734f4fb7..d0932cc81 100644 --- a/packages/appkit-react/src/features/jettons/hooks/use-jetton-wallet-address.ts +++ b/packages/appkit-react/src/features/jettons/hooks/use-jetton-wallet-address.ts @@ -18,16 +18,40 @@ import { useQuery } from '../../../libs/query'; import type { UseQueryReturnType } from '../../../libs/query'; import { useNetwork } from '../../network'; +/** + * Parameters accepted by {@link useJettonWalletAddress} — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the jetton master, owner address and optional network override. + * + * @public + * @category Type + * @section Jettons + */ export type UseJettonWalletAddressParameters = GetJettonWalletAddressQueryConfig; +/** + * Return type of {@link useJettonWalletAddress} — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + * + * @public + * @category Type + * @section Jettons + */ export type UseJettonWalletAddressReturnType = UseQueryReturnType< selectData, GetJettonWalletAddressErrorType >; /** - * Hook to get jetton wallet address + * React hook deriving the owner's jetton-wallet address — the per-owner contract that actually holds the jetton balance for a given master — through TanStack Query. + * + * @param parameters - {@link UseJettonWalletAddressParameters} Jetton master, owner address, optional network override and TanStack Query overrides. + * @expand parameters + * @returns TanStack Query result for the jetton-wallet address read. + * + * @sample docs/examples/src/appkit/hooks/jettons#USE_JETTON_WALLET_ADDRESS + * + * @public + * @category Hook + * @section Jettons */ export const useJettonWalletAddress = ( parameters: UseJettonWalletAddressParameters = {}, diff --git a/packages/appkit-react/src/features/jettons/hooks/use-jettons-by-address.ts b/packages/appkit-react/src/features/jettons/hooks/use-jettons-by-address.ts index 8455e51e9..7d2a8d55f 100644 --- a/packages/appkit-react/src/features/jettons/hooks/use-jettons-by-address.ts +++ b/packages/appkit-react/src/features/jettons/hooks/use-jettons-by-address.ts @@ -14,16 +14,40 @@ import { useQuery } from '../../../libs/query'; import type { UseQueryReturnType } from '../../../libs/query'; import { useNetwork } from '../../network'; +/** + * Parameters accepted by {@link useJettonsByAddress} — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the owner address, optional network override and pagination. + * + * @public + * @category Type + * @section Jettons + */ export type UseJettonsByAddressParameters = GetJettonsByAddressQueryConfig; +/** + * Return type of {@link useJettonsByAddress} — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + * + * @public + * @category Type + * @section Jettons + */ export type UseJettonsByAddressReturnType = UseQueryReturnType< selectData, GetJettonsErrorType >; /** - * Hook to get jettons + * React hook listing jettons held by an arbitrary address through TanStack Query — useful for wallets that aren't selected in AppKit (use {@link useJettons} for the selected wallet). + * + * @param parameters - {@link UseJettonsByAddressParameters} Owner address, optional network override, pagination and TanStack Query overrides. + * @expand parameters + * @returns TanStack Query result for the jettons list. + * + * @sample docs/examples/src/appkit/hooks/jettons#USE_JETTONS_BY_ADDRESS + * + * @public + * @category Hook + * @section Jettons */ export const useJettonsByAddress = ( parameters: UseJettonsByAddressParameters = {}, diff --git a/packages/appkit-react/src/features/jettons/hooks/use-jettons.ts b/packages/appkit-react/src/features/jettons/hooks/use-jettons.ts index bb002e07e..04fbee0f7 100644 --- a/packages/appkit-react/src/features/jettons/hooks/use-jettons.ts +++ b/packages/appkit-react/src/features/jettons/hooks/use-jettons.ts @@ -12,12 +12,36 @@ import { useAddress } from '../../wallets/hooks/use-address'; import { useJettonsByAddress } from './use-jettons-by-address'; import type { UseJettonsByAddressParameters, UseJettonsByAddressReturnType } from './use-jettons-by-address'; +/** + * Parameters accepted by {@link useJettons} — same shape as {@link UseJettonsByAddressParameters}. The hook resolves `address` from the selected wallet and overrides any value supplied here. + * + * @public + * @category Type + * @section Jettons + */ export type UseJettonsParameters = UseJettonsByAddressParameters; +/** + * Return type of {@link useJettons} — TanStack Query result carrying `data`, `isLoading`, `error` and the standard companions. + * + * @public + * @category Type + * @section Jettons + */ export type UseJettonsReturnType = UseJettonsByAddressReturnType; /** - * Hook to get jettons of the selected wallet + * React hook listing jettons held by the currently selected wallet through TanStack Query — auto-resolves the wallet address (use {@link useJettonsByAddress} for an arbitrary address). + * + * @param parameters - {@link UseJettonsParameters} TanStack Query overrides (`select`, `enabled`, `staleTime`, …), pagination and an optional network override. + * @expand parameters + * @returns TanStack Query result for the jettons list. + * + * @sample docs/examples/src/appkit/hooks/jettons#USE_JETTONS + * + * @public + * @category Hook + * @section Jettons */ export const useJettons = ( parameters: UseJettonsParameters = {}, diff --git a/packages/appkit-react/src/features/jettons/hooks/use-transfer-jetton.ts b/packages/appkit-react/src/features/jettons/hooks/use-transfer-jetton.ts index fb797cb94..8e6c39881 100644 --- a/packages/appkit-react/src/features/jettons/hooks/use-transfer-jetton.ts +++ b/packages/appkit-react/src/features/jettons/hooks/use-transfer-jetton.ts @@ -21,8 +21,22 @@ import { useMutation } from '../../../libs/query'; import type { UseMutationReturnType } from '../../../libs/query'; import { useAppKit } from '../../settings'; +/** + * Parameters accepted by {@link useTransferJetton} — TanStack Query mutation options. + * + * @public + * @category Type + * @section Jettons + */ export type UseTransferJettonParameters = TransferJettonOptions; +/** + * Return type of {@link useTransferJetton} — TanStack Query mutation result. + * + * @public + * @category Type + * @section Jettons + */ export type UseTransferJettonReturnType = UseMutationReturnType< TransferJettonData, TransferJettonErrorType, @@ -35,6 +49,19 @@ export type UseTransferJettonReturnType = UseMutationReturnTy MutateFunction >; +/** + * Transfer a jetton from the selected wallet in one step — derives the owner's jetton-wallet from the master address, builds the transfer message, signs it through the wallet and broadcasts it. Call `mutate` with the `jettonAddress` (master), the `recipientAddress`, an `amount` (in jetton units as a human-readable decimal — converted into raw smallest units using `jettonDecimals`), the `jettonDecimals` itself and an optional `comment`. On success, `data` carries the BoC and normalized hash of the broadcast transaction. Throws `Error('Wallet not connected')` if no wallet is currently selected — TanStack Query surfaces it via the mutation's `error`. + * + * @param parameters - {@link UseTransferJettonParameters} TanStack Query mutation overrides. + * @expand parameters + * @returns Mutation result for the jetton transfer call. + * + * @sample docs/examples/src/appkit/hooks/jettons#USE_TRANSFER_JETTON + * + * @public + * @category Hook + * @section Jettons + */ export const useTransferJetton = ( parameters: UseTransferJettonParameters = {}, ): UseTransferJettonReturnType => { diff --git a/packages/appkit-react/src/features/jettons/hooks/use-watch-jettons-by-address.ts b/packages/appkit-react/src/features/jettons/hooks/use-watch-jettons-by-address.ts index 333f9bdc0..f9be69ba5 100644 --- a/packages/appkit-react/src/features/jettons/hooks/use-watch-jettons-by-address.ts +++ b/packages/appkit-react/src/features/jettons/hooks/use-watch-jettons-by-address.ts @@ -14,11 +14,26 @@ import { handleJettonBalanceUpdate, handleJettonsUpdate } from '@ton/appkit/quer import { useAppKit } from '../../settings'; +/** + * Parameters accepted by {@link useWatchJettonsByAddress} — same fields as {@link appkit:WatchJettonsByAddressOptions}, all optional so callers can render the hook before the address is known. + * + * @public + * @category Type + * @section Jettons + */ export type UseWatchJettonsByAddressParameters = Partial; /** - * Hook to watch jetton updates for a specific address in real-time. - * Automatically updates TanStack Query caches for jetton balances. + * Subscribe to jetton-balance updates for an arbitrary owner address. Updates flow into the TanStack Query cache so {@link useJettonsByAddress} and {@link useJettonBalanceByAddress} pick up the new data automatically. Requires a streaming provider registered for the network — the hook exits silently with a console warning when none is configured. + * + * @param parameters - {@link UseWatchJettonsByAddressParameters} Owner address, update callback and optional network override. + * @expand parameters + * + * @sample docs/examples/src/appkit/hooks/jettons#USE_WATCH_JETTONS_BY_ADDRESS + * + * @public + * @category Hook + * @section Jettons */ export const useWatchJettonsByAddress = (parameters: UseWatchJettonsByAddressParameters): void => { const { address, network } = parameters; diff --git a/packages/appkit-react/src/features/jettons/hooks/use-watch-jettons.ts b/packages/appkit-react/src/features/jettons/hooks/use-watch-jettons.ts index 79ece05a3..6dc8a39f1 100644 --- a/packages/appkit-react/src/features/jettons/hooks/use-watch-jettons.ts +++ b/packages/appkit-react/src/features/jettons/hooks/use-watch-jettons.ts @@ -12,11 +12,26 @@ import { useAddress } from '../../wallets/hooks/use-address'; import { useNetwork } from '../../network/hooks/use-network'; import { useWatchJettonsByAddress } from './use-watch-jettons-by-address'; +/** + * Parameters accepted by {@link useWatchJettons} — update callback and optional network override. The hook resolves the address from the selected wallet. + * + * @public + * @category Type + * @section Jettons + */ export type UseWatchJettonsParameters = Partial; /** - * Hook to watch jetton updates of the currently selected wallet in real-time. - * Automatically updates TanStack Query caches for jetton balances. + * Subscribe to jetton-balance updates for the currently selected wallet. Updates flow into the TanStack Query cache so {@link useJettons} picks up the new data automatically (use {@link useWatchJettonsByAddress} for a fixed address). Requires a streaming provider registered for the network — the hook exits silently with a console warning when none is configured. + * + * @param parameters - {@link UseWatchJettonsParameters} Update callback and optional network override. + * @expand parameters + * + * @sample docs/examples/src/appkit/hooks/jettons#USE_WATCH_JETTONS + * + * @public + * @category Hook + * @section Jettons */ export const useWatchJettons = (parameters: UseWatchJettonsParameters = {}): void => { const address = useAddress(); diff --git a/packages/appkit-react/src/features/network/hooks/use-block-number.ts b/packages/appkit-react/src/features/network/hooks/use-block-number.ts index 247edc451..3d4ac6525 100644 --- a/packages/appkit-react/src/features/network/hooks/use-block-number.ts +++ b/packages/appkit-react/src/features/network/hooks/use-block-number.ts @@ -14,15 +14,37 @@ import { useQuery } from '../../../libs/query'; import type { UseQueryReturnType } from '../../../libs/query'; import { useNetwork } from '../hooks/use-network'; +/** + * Parameters accepted by {@link useBlockNumber} — TanStack Query options plus an optional network override. Defaults to the selected wallet's network. If no wallet is selected, falls back to mainnet. + * + * @public + * @category Type + * @section Networks + */ export type UseBlockNumberParameters = GetBlockNumberQueryConfig; +/** + * Return type of {@link useBlockNumber} — TanStack Query result. + * + * @public + * @category Type + * @section Networks + */ export type UseBlockNumberReturnType = UseQueryReturnType< selectData, GetBlockNumberErrorType >; /** - * Hook to get the current masterchain block number + * React hook reading the latest masterchain seqno through TanStack Query — useful for freshness checks and pagination cursors. + * + * @param parameters - {@link UseBlockNumberParameters} TanStack Query overrides and optional network. + * @expand parameters + * @returns TanStack Query result for the seqno read. + * + * @public + * @category Hook + * @section Networks */ export const useBlockNumber = ( parameters: UseBlockNumberParameters = {}, diff --git a/packages/appkit-react/src/features/network/hooks/use-default-network.ts b/packages/appkit-react/src/features/network/hooks/use-default-network.ts index 694b99aed..d6a93c3bc 100644 --- a/packages/appkit-react/src/features/network/hooks/use-default-network.ts +++ b/packages/appkit-react/src/features/network/hooks/use-default-network.ts @@ -12,13 +12,26 @@ import type { GetDefaultNetworkReturnType, Network } from '@ton/appkit'; import { useAppKit } from '../../settings'; +/** + * Return type of {@link useDefaultNetwork} — `[network, setNetwork]` tuple. `network` is the current default (or `undefined`). `setNetwork` calls {@link appkit:setDefaultNetwork} and emits `networks:default-changed`. + * + * @public + * @category Type + * @section Networks + */ export type UseDefaultNetworkReturnType = [ network: GetDefaultNetworkReturnType, setNetwork: (network: Network | undefined) => void, ]; /** - * Hook to get and set the default network for wallet connections. + * Read and write AppKit's default network — the network connectors use for new wallet connections. Returns a `useState`-style tuple. The read side updates when the default changes through any source (this hook, {@link appkit:setDefaultNetwork}, manager events). + * + * @returns Tuple `[network, setNetwork]`. + * + * @public + * @category Hook + * @section Networks */ export const useDefaultNetwork = (): UseDefaultNetworkReturnType => { const appKit = useAppKit(); diff --git a/packages/appkit-react/src/features/network/hooks/use-network.ts b/packages/appkit-react/src/features/network/hooks/use-network.ts index 6128c44f7..6c2ecbf9d 100644 --- a/packages/appkit-react/src/features/network/hooks/use-network.ts +++ b/packages/appkit-react/src/features/network/hooks/use-network.ts @@ -11,10 +11,23 @@ import { useMemo } from 'react'; import { useSelectedWallet } from '../../wallets'; +/** + * Return type of {@link useNetwork} — `undefined` when no wallet is currently selected. + * + * @public + * @category Type + * @section Networks + */ export type UseNetworkReturnType = Network | undefined; /** - * Hook to get network of the selected wallet + * Read the {@link appkit:Network} the selected wallet is connected to. Updates when the wallet's network changes (e.g. user switches mainnet/testnet inside the wallet). + * + * @returns Selected wallet's network, or `undefined` when no wallet is selected. + * + * @public + * @category Hook + * @section Networks */ export const useNetwork = (): UseNetworkReturnType => { const [wallet] = useSelectedWallet(); diff --git a/packages/appkit-react/src/features/network/hooks/use-networks.ts b/packages/appkit-react/src/features/network/hooks/use-networks.ts index 775da117e..aa53b08d2 100644 --- a/packages/appkit-react/src/features/network/hooks/use-networks.ts +++ b/packages/appkit-react/src/features/network/hooks/use-networks.ts @@ -12,10 +12,23 @@ import type { GetNetworksReturnType } from '@ton/appkit'; import { useAppKit } from '../../settings'; +/** + * Return type of {@link useNetworks} — same shape as {@link appkit:GetNetworksReturnType}. + * + * @public + * @category Type + * @section Networks + */ export type UseNetworksReturnType = GetNetworksReturnType; /** - * Hook to get all configured networks + * Read the list of networks configured on AppKit. Updates when {@link appkit:AppKitNetworkManager} adds, replaces or drops a network. + * + * @returns Array of configured {@link appkit:Network}s. + * + * @public + * @category Hook + * @section Networks */ export const useNetworks = (): UseNetworksReturnType => { const appKit = useAppKit(); diff --git a/packages/appkit-react/src/features/nft/components/nft-item/nft-item.tsx b/packages/appkit-react/src/features/nft/components/nft-item/nft-item.tsx index 7c26830b1..54d050333 100644 --- a/packages/appkit-react/src/features/nft/components/nft-item/nft-item.tsx +++ b/packages/appkit-react/src/features/nft/components/nft-item/nft-item.tsx @@ -16,10 +16,27 @@ import { ImageIcon } from '../../../../components/ui/icons'; import { useI18n } from '../../../settings/hooks/use-i18n'; import styles from './nft-item.module.css'; +/** + * Props accepted by {@link NftItem} — extends the native ` diff --git a/packages/appkit-react/src/features/staking/components/staking-info/staking-info.tsx b/packages/appkit-react/src/features/staking/components/staking-info/staking-info.tsx index 042a65b87..e1f7f7b69 100644 --- a/packages/appkit-react/src/features/staking/components/staking-info/staking-info.tsx +++ b/packages/appkit-react/src/features/staking/components/staking-info/staking-info.tsx @@ -14,15 +14,35 @@ import { InfoBlock } from '../../../../components/ui/info-block'; import { useI18n } from '../../../settings/hooks/use-i18n'; import { formatAmount } from './utils'; +/** + * Props accepted by {@link StakingInfo}. + * + * @public + * @category Type + * @section Staking + */ export interface StakingInfoProps extends ComponentProps { + /** Current staking quote — its `amountOut` is rendered in the "You get" row. */ quote: StakingQuote | undefined; + /** True while the quote is being fetched. Swaps the "You get" value for a skeleton. */ isQuoteLoading: boolean; + /** Dynamic provider info — supplies APY and exchange rate. */ providerInfo: StakingProviderInfo | undefined; + /** Static provider metadata — supplies token tickers/decimals and the provider name. */ providerMetadata: StakingProviderMetadata | undefined; + /** True while provider info is being fetched. */ isProviderInfoLoading: boolean; + /** Operation direction — controls which token's decimals/ticker label the "You get" amount. Defaults to `'stake'`. */ direction?: StakingQuoteDirection; } +/** + * Summary block rendered below the staking input. Shows the amount the user will receive, the provider's current APY, the stake-token to receive-token exchange rate (only when the provider has a receive token), and the provider name. The exchange-rate row always reads as `1 stakeToken = X receiveToken`, regardless of `direction`. + * + * @public + * @category Component + * @section Staking + */ export const StakingInfo: FC = ({ quote, isQuoteLoading, diff --git a/packages/appkit-react/src/features/staking/components/staking-settings-modal/staking-settings-modal.tsx b/packages/appkit-react/src/features/staking/components/staking-settings-modal/staking-settings-modal.tsx index a881b5017..a15351457 100644 --- a/packages/appkit-react/src/features/staking/components/staking-settings-modal/staking-settings-modal.tsx +++ b/packages/appkit-react/src/features/staking/components/staking-settings-modal/staking-settings-modal.tsx @@ -16,12 +16,25 @@ import { OptionSwitcher } from '../../../../components/shared/option-switcher'; import { useI18n } from '../../../settings/hooks/use-i18n'; import styles from './staking-settings-modal.module.css'; +/** + * Props accepted by {@link StakingSettingsModal}. + * + * @public + * @category Type + * @section Staking + */ export interface StakingSettingsModalProps { + /** Controls modal visibility. */ open: boolean; + /** Called when the user dismisses the modal or after a successful save. */ onClose: () => void; + /** Currently active staking provider — used to preselect the option when the modal opens. */ provider: StakingProvider | undefined; + /** All registered staking providers to choose from. */ providers: StakingProvider[]; + /** Invoked with the chosen `providerId` when the user saves a different selection. */ onProviderChange: (providerId: string) => void; + /** Network used to resolve each provider's display name via its metadata. */ network?: Network; } @@ -33,6 +46,15 @@ const getProviderName = (provider: StakingProvider, network?: Network): string = } }; +/** + * Modal that lets the user pick the active staking provider. The selection is staged locally and only committed via `onProviderChange` when the user presses `Save`. Closing the modal otherwise discards the change. Each option is labeled with the provider's metadata `name`, falling back to its `providerId` if metadata is unavailable on the given network. + * + * @sample docs/examples/src/appkit/components/staking#STAKING_SETTINGS_MODAL + * + * @public + * @category Component + * @section Staking + */ export const StakingSettingsModal: FC = ({ open, onClose, diff --git a/packages/appkit-react/src/features/staking/components/staking-widget-provider/staking-widget-provider.tsx b/packages/appkit-react/src/features/staking/components/staking-widget-provider/staking-widget-provider.tsx index 3bef2a947..f64e8cd10 100644 --- a/packages/appkit-react/src/features/staking/components/staking-widget-provider/staking-widget-provider.tsx +++ b/packages/appkit-react/src/features/staking/components/staking-widget-provider/staking-widget-provider.tsx @@ -43,8 +43,11 @@ import { useDebounceValue } from '../../../../hooks/use-debounce-value'; import { useStakingValidation } from './use-staking-validation'; /** - * Context type for the StakingWidget. - * Provides all necessary state and actions for building custom staking UIs. + * Shape of the staking context exposed by {@link StakingWidgetProvider} and read via {@link useStakingContext}. Aggregates inputs (amount, direction, unstake mode), fetched data (balances, quote, provider info/metadata), derived flags (`canSubmit`, `error`, loading states), and the actions used by {@link StakingWidgetUI} (send transaction, switch provider, max, low-balance handling). + * + * @public + * @category Type + * @section Staking */ export interface StakingContextType { /** Amount the user wants to stake (string to preserve input UX) */ @@ -81,7 +84,7 @@ export interface StakingContextType { stakedBalance: StakingBalance | undefined; /** True while staked balance is being fetched */ isStakedBalanceLoading: boolean; - /** Selected unstake mode (e.g. instant or delayed) */ + /** Selected unstake-timing mode — `'INSTANT'`, `'WHEN_AVAILABLE'`, or `'ROUND_END'`. See {@link appkit:UnstakeMode}. */ unstakeMode: UnstakeModes; /** Sets the input amount */ setAmount: (amount: string) => void; @@ -107,9 +110,9 @@ export interface StakingContextType { lowBalanceMode: 'reduce' | 'topup'; /** Required TON amount for the pending operation, formatted as a decimal string. Empty when no pending op. */ lowBalanceRequiredTon: string; - /** Replace the input with a value that fits into the current TON balance and close the warning */ + /** Replace the input with a value that fits within the current TON balance and close the warning. */ onLowBalanceChange: () => void; - /** Dismiss the low-balance warning without changing the input */ + /** Dismiss the low-balance warning without changing the input. */ onLowBalanceCancel: () => void; } @@ -149,24 +152,35 @@ export const StakingContext = createContext({ }); /** - * Hook to access the staking context. - * Must be used within a StakingWidgetProvider (or StakingWidget). + * Reads the {@link StakingContextType} from the nearest {@link StakingWidgetProvider} (or {@link StakingWidget}). Outside a provider, returns the default context (empty inputs, no-op actions) so a custom UI can still mount without crashing. + * + * @public + * @category Hook + * @section Staking */ export const useStakingContext = () => { return useContext(StakingContext); }; /** - * Props for the StakingWidgetProvider. + * Props accepted by {@link StakingWidgetProvider}. + * + * @public + * @category Type + * @section Staking */ export interface StakingProviderProps extends PropsWithChildren { - /** - * Network to use for quote fetching and transactions. - * When omitted, uses the selected wallet's network. - */ + /** Network used for quote fetching, balance reads, and transactions. Falls back to the connected wallet's network when omitted. */ network?: Network; } +/** + * Headless provider that drives the staking-widget flow — owns the input state (amount, direction, unstake mode, reverse-input toggle), fetches quotes and balances, validates the input, and builds + submits the transaction with a low-balance guard. Children read everything through {@link useStakingContext}; pair with {@link StakingWidgetUI} (or pass a custom UI to {@link StakingWidget}'s `children`). + * + * @public + * @category Component + * @section Staking + */ export const StakingWidgetProvider: FC = ({ children, network: networkProp }) => { const [amount, setAmountRaw] = useState(''); const [unstakeMode, setUnstakeMode] = useState(UnstakeMode.INSTANT); diff --git a/packages/appkit-react/src/features/staking/components/staking-widget-ui/staking-widget-ui.tsx b/packages/appkit-react/src/features/staking/components/staking-widget-ui/staking-widget-ui.tsx index 35c6b0e7e..7dd51d344 100644 --- a/packages/appkit-react/src/features/staking/components/staking-widget-ui/staking-widget-ui.tsx +++ b/packages/appkit-react/src/features/staking/components/staking-widget-ui/staking-widget-ui.tsx @@ -25,8 +25,22 @@ import { AmountReversed } from '../../../../components/ui/amount-reversed'; import { LowBalanceModal } from '../../../../components/shared/low-balance-modal'; import { SettingsButton } from '../../../../components/shared/settings-button'; +/** + * Props accepted by {@link StakingWidgetUI} (also the argument type for the `StakingWidget` render-prop). Combines the full {@link StakingContextType} with standard `
          ` props forwarded to the outer wrapper. + * + * @public + * @category Type + * @section Staking + */ export type StakingWidgetRenderProps = StakingContextType & ComponentProps<'div'>; +/** + * Default staking-widget UI. Renders a stake/unstake tabbed layout: a centered amount input with optional reversed input, a {@link StakingBalanceBlock} for the relevant balance, the submit button (wired through `ButtonWithConnect` so a disconnected user is prompted to connect first), a settings button that opens {@link StakingSettingsModal}, the unstake-mode picker ({@link SelectUnstakeMode}, unstake tab only), and a {@link StakingInfo} summary. A {@link LowBalanceModal} surfaces when the built transaction would exceed the user's TON balance. All state is consumed from props — typically supplied by {@link StakingWidgetProvider}. + * + * @public + * @category Component + * @section Staking + */ export const StakingWidgetUI: FC = ({ amount, canSubmit, diff --git a/packages/appkit-react/src/features/staking/components/staking-widget/staking-widget.tsx b/packages/appkit-react/src/features/staking/components/staking-widget/staking-widget.tsx index e0ef2d3c0..c12603725 100644 --- a/packages/appkit-react/src/features/staking/components/staking-widget/staking-widget.tsx +++ b/packages/appkit-react/src/features/staking/components/staking-widget/staking-widget.tsx @@ -14,14 +14,16 @@ import { StakingWidgetProvider, useStakingContext } from '../staking-widget-prov import type { StakingProviderProps } from '../staking-widget-provider'; /** - * Props for the StakingWidget component. + * Props accepted by {@link StakingWidget}. Extends {@link StakingProviderProps} (e.g. `network`) and standard `
          ` props forwarded to the default UI. + * + * @public + * @category Type + * @section Staking */ export interface StakingWidgetProps extends Omit, Omit, 'children'> { /** - * Custom render function. - * When provided, it replaces the default widget UI and gives full control over the rendering. - * Useful for building unique staking interfaces while leveraging the widget's internal logic. + * Optional render-prop. When provided, the default {@link StakingWidgetUI} is bypassed and this function is called with the full {@link StakingWidgetRenderProps} (context state + forwarded `
          ` props), letting consumers build a custom UI on top of the widget's internal logic. */ children?: (props: StakingWidgetRenderProps) => ReactNode; } @@ -39,11 +41,13 @@ const StakingWidgetContent: FC< }; /** - * A high-level component that provides a complete staking interface. + * High-level staking widget that wires the full stake/unstake flow: pick a provider, enter an amount (with optional reverse input on supported providers), review the quote (APY, exchange rate, "you get"), then submit the transaction. Internally wraps {@link StakingWidgetProvider} around {@link StakingWidgetUI}. Consumers can replace the UI by passing a render-prop `children` while keeping the widget's state, quoting, balance checks, and submission logic. + * + * @sample docs/examples/src/appkit/components/staking#STAKING_WIDGET * - * It manages the staking lifecycle, including fetching quotes, building transactions, - * and handling user input. It can be used as a standalone widget with default UI - * or customized using a render function. + * @public + * @category Component + * @section Staking */ export const StakingWidget: FC = ({ children, network, ...rest }) => { return ( diff --git a/packages/appkit-react/src/features/staking/hooks/use-build-stake-transaction.ts b/packages/appkit-react/src/features/staking/hooks/use-build-stake-transaction.ts index c0b5e7250..ab2df164d 100644 --- a/packages/appkit-react/src/features/staking/hooks/use-build-stake-transaction.ts +++ b/packages/appkit-react/src/features/staking/hooks/use-build-stake-transaction.ts @@ -17,6 +17,13 @@ import type { import { useAppKit } from '../../settings'; import { useMutation } from '../../../libs/query'; +/** + * Return type of {@link useBuildStakeTransaction} — TanStack Query mutation result that resolves to a {@link appkit:TransactionRequest}. + * + * @public + * @category Type + * @section Staking + */ export type UseBuildStakeTransactionReturnType = UseMutationResult< BuildStakeTransactionData, BuildStakeTransactionErrorType, @@ -25,7 +32,13 @@ export type UseBuildStakeTransactionReturnType = UseMutationR >; /** - * Hook to build stake transaction + * Build a stake/unstake {@link appkit:TransactionRequest} from a {@link appkit:StakingQuote} (obtained via {@link useStakingQuote}) without sending it — lets the UI inspect, batch, or pass the request to {@link useSendTransaction} separately. Call `mutate(params)` where `params` matches {@link appkit:BuildStakeTransactionOptions} (quote + user address, optional provider override). The resulting `TransactionRequest` is in `data` once the mutation resolves. + * + * @returns Mutation result for the build call. + * + * @public + * @category Hook + * @section Staking */ export const useBuildStakeTransaction = (): UseBuildStakeTransactionReturnType => { const appKit = useAppKit(); diff --git a/packages/appkit-react/src/features/staking/hooks/use-staked-balance.ts b/packages/appkit-react/src/features/staking/hooks/use-staked-balance.ts index da7899378..38e360276 100644 --- a/packages/appkit-react/src/features/staking/hooks/use-staked-balance.ts +++ b/packages/appkit-react/src/features/staking/hooks/use-staked-balance.ts @@ -14,14 +14,37 @@ import { useQuery } from '../../../libs/query'; import type { UseQueryReturnType } from '../../../libs/query'; import { useNetwork } from '../../network'; +/** + * Parameters accepted by {@link useStakedBalance} — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the owner address, optional network override and optional `providerId`. + * + * @public + * @category Type + * @section Staking + */ export type UseStakedBalanceParameters = GetStakedBalanceQueryConfig; + +/** + * Return type of {@link useStakedBalance} — TanStack Query result carrying the user's staked balance. + * + * @public + * @category Type + * @section Staking + */ export type UseStakedBalanceReturnType = UseQueryReturnType< selectData, GetStakedBalanceErrorType >; /** - * Hook to get user's staked balance + * React hook reading a user's staked balance from a staking provider through TanStack Query — total staked plus, depending on the provider, any instant-unstake balance available right now. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. + * + * @param parameters - {@link UseStakedBalanceParameters} Owner address, optional `providerId`, optional network override, and TanStack Query overrides. + * @expand parameters + * @returns TanStack Query result for the staked-balance read. + * + * @public + * @category Hook + * @section Staking */ export const useStakedBalance = ( parameters: UseStakedBalanceParameters = {}, diff --git a/packages/appkit-react/src/features/staking/hooks/use-staking-provider-info.ts b/packages/appkit-react/src/features/staking/hooks/use-staking-provider-info.ts index 39a7f5c96..0f0bf114e 100644 --- a/packages/appkit-react/src/features/staking/hooks/use-staking-provider-info.ts +++ b/packages/appkit-react/src/features/staking/hooks/use-staking-provider-info.ts @@ -19,15 +19,38 @@ import type { UseQueryReturnType } from '../../../libs/query'; import { useNetwork } from '../../network'; import { useStakingProvider } from './use-staking-provider'; +/** + * Parameters accepted by {@link useStakingProviderInfo} — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus an optional `providerId` and network override. + * + * @public + * @category Type + * @section Staking + */ export type UseStakingProviderInfoParameters = GetStakingProviderInfoQueryConfig; + +/** + * Return type of {@link useStakingProviderInfo} — TanStack Query result carrying live {@link appkit:StakingProviderInfo}. + * + * @public + * @category Type + * @section Staking + */ export type UseStakingProviderInfoReturnType = UseQueryReturnType< selectData, GetStakingProviderInfoErrorType >; /** - * Hook to get staking provider information + * React hook reading live staking-pool info for a provider through TanStack Query — APY, instant-unstake liquidity and (for liquid staking) the current exchange rate. Use {@link useStakingProviderMetadata} for static metadata (name, stake/receive tokens, supported unstake modes). Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. + * + * @param parameters - {@link UseStakingProviderInfoParameters} Optional `providerId`, network override, and TanStack Query overrides. + * @expand parameters + * @returns TanStack Query result for the live provider info. + * + * @public + * @category Hook + * @section Staking */ export const useStakingProviderInfo = ( parameters: UseStakingProviderInfoParameters = {}, @@ -38,8 +61,8 @@ export const useStakingProviderInfo = ( return useQuery( getStakingProviderInfoQueryOptions(appKit, { - providerId: provider?.providerId, ...parameters, + providerId: parameters.providerId ?? provider?.providerId, network: parameters.network ?? walletNetwork, }), ); diff --git a/packages/appkit-react/src/features/staking/hooks/use-staking-provider-metadata.ts b/packages/appkit-react/src/features/staking/hooks/use-staking-provider-metadata.ts index 3563ecfad..d8a159241 100644 --- a/packages/appkit-react/src/features/staking/hooks/use-staking-provider-metadata.ts +++ b/packages/appkit-react/src/features/staking/hooks/use-staking-provider-metadata.ts @@ -13,11 +13,34 @@ import { useMemo } from 'react'; import { useAppKit } from '../../settings'; import { useStakingProvider } from './use-staking-provider'; +/** + * Parameters accepted by {@link useStakingProviderMetadata} — optional `providerId` and network override. + * + * @public + * @category Type + * @section Staking + */ export type UseStakingProviderMetadataParameters = GetStakingProviderMetadataOptions; -export type UseStakingProviderMetadataReturnType = GetStakingProviderMetadataReturnType; /** - * Hook to get static staking provider metadata + * Return type of {@link useStakingProviderMetadata} — static {@link appkit:StakingProviderMetadata} for the resolved provider, or `undefined` when no provider matches and no default is registered (the hook swallows the throw from {@link appkit:getStakingProviderMetadata}). + * + * @public + * @category Type + * @section Staking + */ +export type UseStakingProviderMetadataReturnType = GetStakingProviderMetadataReturnType | undefined; + +/** + * Read static metadata for a staking provider — display name, stake/receive tokens, supported unstake modes and contract address. Returns `undefined` when no provider matches and no default is registered. Use {@link useStakingProviderInfo} for live values (APY, instant-unstake liquidity, exchange rate). Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. + * + * @param parameters - {@link UseStakingProviderMetadataParameters} Optional `providerId` and network override. + * @expand parameters + * @returns Static {@link appkit:StakingProviderMetadata}, or `undefined` when the provider can't be resolved. + * + * @public + * @category Hook + * @section Staking */ export const useStakingProviderMetadata = (parameters: UseStakingProviderMetadataParameters = {}) => { const appKit = useAppKit(); diff --git a/packages/appkit-react/src/features/staking/hooks/use-staking-provider.ts b/packages/appkit-react/src/features/staking/hooks/use-staking-provider.ts index f9204a376..7af7b29a9 100644 --- a/packages/appkit-react/src/features/staking/hooks/use-staking-provider.ts +++ b/packages/appkit-react/src/features/staking/hooks/use-staking-provider.ts @@ -12,16 +12,38 @@ import type { GetStakingProviderOptions, GetStakingProviderReturnType } from '@t import { useAppKit } from '../../settings/hooks/use-app-kit'; -export type UseStakingProviderReturnType = GetStakingProviderReturnType; +/** + * Parameters accepted by {@link useStakingProvider} — optional provider id forwarded to {@link appkit:getStakingProvider}. + * + * @public + * @category Type + * @section Staking + */ +export type UseStakingProviderParameters = GetStakingProviderOptions; /** - * Hook to get staking provider + * Return type of {@link useStakingProvider} — the matching staking provider, or `undefined` when none resolves (the hook swallows the throw from {@link appkit:getStakingProvider}). + * + * @public + * @category Type + * @section Staking + */ +export type UseStakingProviderReturnType = GetStakingProviderReturnType | undefined; + +/** + * React hook returning a registered staking provider. Subscribes to provider-registry changes via {@link appkit:watchStakingProviders} and looks up by `id`, or returns the registered default when no id is given. Returns `undefined` when no provider matches and no default has been registered (where the underlying {@link appkit:getStakingProvider} action would throw). + * + * @param parameters - {@link UseStakingProviderParameters} Optional provider id. + * @expand parameters + * @returns Matching staking provider instance, or `undefined` when none resolves. + * + * @public + * @category Hook + * @section Staking */ -export const useStakingProvider = ( - options: GetStakingProviderOptions = {}, -): UseStakingProviderReturnType | undefined => { +export const useStakingProvider = (parameters: UseStakingProviderParameters = {}): UseStakingProviderReturnType => { const appKit = useAppKit(); - const { id } = options; + const { id } = parameters; const subscribe = useCallback( (onChange: () => void) => { diff --git a/packages/appkit-react/src/features/staking/hooks/use-staking-providers.ts b/packages/appkit-react/src/features/staking/hooks/use-staking-providers.ts index 171964eb9..18cef7310 100644 --- a/packages/appkit-react/src/features/staking/hooks/use-staking-providers.ts +++ b/packages/appkit-react/src/features/staking/hooks/use-staking-providers.ts @@ -12,10 +12,23 @@ import type { GetStakingProvidersReturnType } from '@ton/appkit'; import { useAppKit } from '../../settings'; +/** + * Return type of {@link useStakingProviders} — array of registered staking providers. + * + * @public + * @category Type + * @section Staking + */ export type UseStakingProvidersReturnType = GetStakingProvidersReturnType; /** - * Hook to get all registered staking providers. + * React hook returning every staking provider registered on the AppKit instance (both those passed via config and those added later). Subscribes to provider-registry changes via {@link appkit:watchStakingProviders}. + * + * @returns Array of registered staking providers. + * + * @public + * @category Hook + * @section Staking */ export const useStakingProviders = (): UseStakingProvidersReturnType => { const appKit = useAppKit(); diff --git a/packages/appkit-react/src/features/staking/hooks/use-staking-quote.ts b/packages/appkit-react/src/features/staking/hooks/use-staking-quote.ts index 63b6cf409..2ec76e340 100644 --- a/packages/appkit-react/src/features/staking/hooks/use-staking-quote.ts +++ b/packages/appkit-react/src/features/staking/hooks/use-staking-quote.ts @@ -14,14 +14,37 @@ import { useQuery } from '../../../libs/query'; import type { UseQueryReturnType } from '../../../libs/query'; import { useNetwork } from '../../network'; +/** + * Parameters accepted by {@link useStakingQuote} — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus stake/unstake amount, direction, target asset and optional `providerId`/network override. + * + * @public + * @category Type + * @section Staking + */ export type UseStakingQuoteParameters = GetStakingQuoteQueryConfig; + +/** + * Return type of {@link useStakingQuote} — TanStack Query result carrying a {@link appkit:StakingQuote}. + * + * @public + * @category Type + * @section Staking + */ export type UseStakingQuoteReturnType = UseQueryReturnType< selectData, GetStakingQuoteErrorType >; /** - * Hook to get staking/unstaking quote + * Quote a stake or unstake — given an amount, direction (`'stake'` / `'unstake'`) and the target asset, returns the rate, expected output and the provider-specific metadata required to feed {@link useBuildStakeTransaction}. `data` is the {@link appkit:StakingQuote} payload. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. + * + * @param parameters - {@link UseStakingQuoteParameters} Quote parameters, optional `providerId`, optional network override, and TanStack Query overrides. + * @expand parameters + * @returns TanStack Query result for the quote read. + * + * @public + * @category Hook + * @section Staking */ export const useStakingQuote = ( parameters: UseStakingQuoteParameters = {}, diff --git a/packages/appkit-react/src/features/staking/index.ts b/packages/appkit-react/src/features/staking/index.ts index 252ce9a79..cc81d3896 100644 --- a/packages/appkit-react/src/features/staking/index.ts +++ b/packages/appkit-react/src/features/staking/index.ts @@ -9,7 +9,11 @@ export { UnstakeMode, type UnstakeModes } from '@ton/appkit'; export { useStakingProviders, type UseStakingProvidersReturnType } from './hooks/use-staking-providers'; -export { useStakingProvider, type UseStakingProviderReturnType } from './hooks/use-staking-provider'; +export { + useStakingProvider, + type UseStakingProviderParameters, + type UseStakingProviderReturnType, +} from './hooks/use-staking-provider'; export { useStakingQuote, type UseStakingQuoteParameters, diff --git a/packages/appkit-react/src/features/swap/components/swap-field/swap-field.stories.tsx b/packages/appkit-react/src/features/swap/components/swap-field/swap-field.stories.tsx index acb9ec4ac..9fd3590e8 100644 --- a/packages/appkit-react/src/features/swap/components/swap-field/swap-field.stories.tsx +++ b/packages/appkit-react/src/features/swap/components/swap-field/swap-field.stories.tsx @@ -26,7 +26,6 @@ export const Pay: Story = { amount: '10', balance: '100000000000', onAmountChange: () => {}, - isWalletConnected: true, }, }; @@ -36,7 +35,6 @@ export const Receive: Story = { token: STORY_TOKENS[1], // USDT amount: '25', balance: '500000000', - isWalletConnected: true, }, }; @@ -46,10 +44,3 @@ export const Loading: Story = { loading: true, }, }; - -export const NoWallet: Story = { - args: { - ...Pay.args, - isWalletConnected: false, - }, -}; diff --git a/packages/appkit-react/src/features/swap/components/swap-field/swap-field.tsx b/packages/appkit-react/src/features/swap/components/swap-field/swap-field.tsx index 5c579deb9..7c2439fd8 100644 --- a/packages/appkit-react/src/features/swap/components/swap-field/swap-field.tsx +++ b/packages/appkit-react/src/features/swap/components/swap-field/swap-field.tsx @@ -18,20 +18,45 @@ import type { AppkitUIToken } from '../../../../types/appkit-ui-token'; import { getDisplayAmount } from '../../utils/get-display-amount'; import styles from './swap-field.module.css'; +/** + * Props accepted by {@link SwapField} — a single source/target row inside the swap widget that hosts the amount input, token picker trigger, fiat conversion and balance line. + * + * @public + * @category Type + * @section Swap + */ export interface SwapFieldProps extends Omit, 'children'> { + /** `pay` renders the editable source row with a "max" shortcut. `receive` renders the read-only target row. */ type: 'pay' | 'receive'; + /** Current amount shown in the input as a human-readable decimal string. */ amount: string; + /** Fiat currency symbol displayed in front of the converted value. Defaults to `"$"`. */ fiatSymbol?: string; + /** Currently selected token. Controls the token selector label, balance formatting and fiat conversion. */ token?: AppkitUIToken; + /** Called with the raw input value when the user edits the amount. Only fired for `type: "pay"`. */ onAmountChange?: (value: string) => void; + /** Formatted balance of `token` for the active wallet, as a human-readable decimal string. Rendered in the balance line beneath the input. */ balance?: string; + /** When true, the balance area renders a skeleton placeholder instead of the value. */ isBalanceLoading?: boolean; + /** When true, the underlying input renders its loading state — used while a fresh quote is in flight. */ loading?: boolean; + /** Called when the user clicks the "max" shortcut to fill the maximum spendable amount. */ onMaxClick?: () => void; + /** Called when the user clicks the token selector chip — typically opens a `SwapTokenSelectModal`. */ onTokenSelectorClick?: () => void; - isWalletConnected?: boolean; } +/** + * One row of the swap form. Renders the amount input, fiat conversion, balance line, and a token-selector chip. The `pay` variant is editable and exposes a "max" shortcut. The `receive` variant is read-only and shows the quote result. + * + * @sample docs/examples/src/appkit/components/swap#SWAP_FIELD + * + * @public + * @category Component + * @section Swap + */ export const SwapField: FC = ({ type, token, @@ -42,7 +67,6 @@ export const SwapField: FC = ({ loading, onMaxClick, onTokenSelectorClick, - isWalletConnected, fiatSymbol = '$', className, ...props diff --git a/packages/appkit-react/src/features/swap/components/swap-flip-button/swap-flip-button.tsx b/packages/appkit-react/src/features/swap/components/swap-flip-button/swap-flip-button.tsx index 3ddf3f305..febe6528c 100644 --- a/packages/appkit-react/src/features/swap/components/swap-flip-button/swap-flip-button.tsx +++ b/packages/appkit-react/src/features/swap/components/swap-flip-button/swap-flip-button.tsx @@ -13,11 +13,29 @@ import styles from './swap-flip-button.module.css'; import { Button } from '../../../../components/ui/button'; import { FlipIcon } from '../../../../components/ui/icons'; +/** + * Props accepted by {@link SwapFlipButton} — the round button placed between the two {@link SwapField} rows that swaps the source and target tokens. + * + * @public + * @category Type + * @section Swap + */ export interface SwapFlipButtonProps extends ComponentProps<'div'> { + /** Called when the user clicks the button. Wire this to a handler that swaps the source/target tokens (e.g. `onFlip` from the swap context). */ onClick?: () => void; + /** When true, the icon is drawn in its rotated state — used to animate between flips. */ rotated?: boolean; } +/** + * Round button rendered between the source and target {@link SwapField} rows. Clicking it flips the selected tokens. Visual rotation is driven by `rotated`. + * + * @sample docs/examples/src/appkit/components/swap#SWAP_FLIP_BUTTON + * + * @public + * @category Component + * @section Swap + */ export const SwapFlipButton: FC = ({ onClick, rotated, className, ...props }) => { return (
          diff --git a/packages/appkit-react/src/features/swap/components/swap-info/swap-info.tsx b/packages/appkit-react/src/features/swap/components/swap-info/swap-info.tsx index 463385540..d59ba4193 100644 --- a/packages/appkit-react/src/features/swap/components/swap-info/swap-info.tsx +++ b/packages/appkit-react/src/features/swap/components/swap-info/swap-info.tsx @@ -14,14 +14,35 @@ import { useI18n } from '../../../settings/hooks/use-i18n'; import type { AppkitUIToken } from '../../../../types/appkit-ui-token'; import { getDisplayAmount } from '../../utils/get-display-amount'; +/** + * Props accepted by {@link SwapInfo} — the summary block under the swap form that surfaces minimum received, slippage and the chosen provider. + * + * @public + * @category Type + * @section Swap + */ export interface SwapInfoProps extends ComponentProps { + /** Target token the user is receiving. Used to format `minReceived` with the right decimals and symbol. */ toToken: AppkitUIToken | null; + /** Slippage tolerance in basis points (`100` = 1%). Rendered as a percentage. */ slippage: number; + /** Current {@link appkit:SwapProvider}. Its display name is shown in the provider row. */ provider?: SwapProvider; + /** Quote whose `minReceived` value is displayed. When undefined the value falls back to `0` (still suffixed with the token symbol). */ quote?: SwapQuote; + /** When true, the minimum-received value renders a skeleton placeholder instead of the formatted number. */ isQuoteLoading?: boolean; } +/** + * Summary block rendered under the swap form. Shows the minimum amount the user is guaranteed to receive after slippage, the configured slippage tolerance, and the active {@link appkit:SwapProvider}. + * + * @sample docs/examples/src/appkit/components/swap#SWAP_INFO + * + * @public + * @category Component + * @section Swap + */ export const SwapInfo: FC = ({ quote, provider, toToken, slippage, isQuoteLoading, ...props }) => { const { t } = useI18n(); diff --git a/packages/appkit-react/src/features/swap/components/swap-settings-modal/swap-settings-modal.tsx b/packages/appkit-react/src/features/swap/components/swap-settings-modal/swap-settings-modal.tsx index 277ff8db8..0fdaf396e 100644 --- a/packages/appkit-react/src/features/swap/components/swap-settings-modal/swap-settings-modal.tsx +++ b/packages/appkit-react/src/features/swap/components/swap-settings-modal/swap-settings-modal.tsx @@ -23,16 +23,37 @@ const formatSlippage = (bps: number): string => `${(bps / 100).toFixed(2)}%`; const SLIPPAGE_OPTIONS = SLIPPAGE_PRESETS.map((bps) => ({ value: String(bps), label: formatSlippage(bps) })); +/** + * Props accepted by `SwapSettingsModal` — the modal that lets the user pick a {@link appkit:SwapProvider} and a slippage preset before confirming a swap. + * + * @public + * @category Type + * @section Swap + */ export interface SwapSettingsModalProps { + /** Controls modal visibility. */ open: boolean; + /** Called when the user dismisses the modal (close icon, overlay click, or after pressing "save"). */ onClose: () => void; + /** Current slippage tolerance in basis points (`100` = 1%). Seeds the staged value when the modal opens. */ slippage: number; + /** Called with the newly selected slippage in basis points when the user presses "save". */ onSlippageChange: (bps: number) => void; + /** Currently active swap provider. Its `providerId` seeds the staged selection. */ provider: SwapProvider | undefined; + /** All swap providers available for selection — each gets a switcher option. */ providers: SwapProvider[]; + /** Called with the newly selected `providerId` when the user presses "save". */ onProviderChange: (providerId: string) => void; } +/** + * Modal that exposes per-swap settings: the {@link appkit:SwapProvider} and a slippage preset. Selections are staged locally and committed via `onSlippageChange` / `onProviderChange` only when the user presses "save". Closing without saving discards them. + * + * @public + * @category Component + * @section Swap + */ export const SwapSettingsModal: FC = ({ open, onClose, diff --git a/packages/appkit-react/src/features/swap/components/swap-token-select-modal/swap-token-select-modal.tsx b/packages/appkit-react/src/features/swap/components/swap-token-select-modal/swap-token-select-modal.tsx index 05a849ada..74f61175c 100644 --- a/packages/appkit-react/src/features/swap/components/swap-token-select-modal/swap-token-select-modal.tsx +++ b/packages/appkit-react/src/features/swap/components/swap-token-select-modal/swap-token-select-modal.tsx @@ -12,8 +12,22 @@ import { TokenSelectModal } from '../../../../components/shared/token-select-mod import type { TokenSelectModalProps } from '../../../../components/shared/token-select-modal'; import { useI18n } from '../../../settings/hooks/use-i18n'; +/** + * Props accepted by `SwapTokenSelectModal` — same shape as the underlying {@link TokenSelectModalProps} but with the title and search placeholder fixed to the swap-flow strings. + * + * @public + * @category Type + * @section Swap + */ export type SwapTokenSelectModalProps = Omit; +/** + * Token picker used by the swap widget — thin wrapper around the shared `TokenSelectModal` that hard-codes the swap-specific title and search placeholder. + * + * @public + * @category Component + * @section Swap + */ export const SwapTokenSelectModal: FC = (props) => { const { t } = useI18n(); diff --git a/packages/appkit-react/src/features/swap/components/swap-widget-provider/swap-widget-provider.tsx b/packages/appkit-react/src/features/swap/components/swap-widget-provider/swap-widget-provider.tsx index b4179f591..02ef5480d 100644 --- a/packages/appkit-react/src/features/swap/components/swap-widget-provider/swap-widget-provider.tsx +++ b/packages/appkit-react/src/features/swap/components/swap-widget-provider/swap-widget-provider.tsx @@ -35,8 +35,11 @@ import { useSwapValidation } from './use-swap-validation'; export type { AppkitUIToken }; /** - * Context type for the SwapWidget. - * Provides all necessary state and actions for building custom swap UIs. + * Shape of the value exposed by {@link useSwapContext}. Holds the selected source/target tokens, the entered amount and the latest quote, balance readouts, validation state, slippage / provider settings, and the callbacks needed to mutate them or to submit the swap transaction. + * + * @public + * @category Type + * @section Swap */ export interface SwapContextType { /** Full list of available tokens for swapping */ @@ -99,9 +102,9 @@ export interface SwapContextType { lowBalanceMode: 'reduce' | 'topup'; /** Required TON amount for the pending operation, formatted as a decimal string. Empty when no pending op. */ lowBalanceRequiredTon: string; - /** Replace the input with a value that fits into the current TON balance and close the warning */ + /** Replace the input with a value that fits within the current TON balance and close the warning. */ onLowBalanceChange: () => void; - /** Dismiss the low-balance warning without changing the input */ + /** Dismiss the low-balance warning without changing the input. */ onLowBalanceCancel: () => void; } @@ -141,34 +144,47 @@ export const SwapContext = createContext({ }); /** - * Hook to access the swap context. - * Must be used within a SwapWidgetProvider (or SwapWidget). + * Reads the {@link SwapContextType} populated by the nearest {@link SwapWidgetProvider} (or the {@link SwapWidget} that mounts one). Outside a provider it returns the no-op default value. + * + * @public + * @category Hook + * @section Swap */ export const useSwapContext = () => { return useContext(SwapContext); }; /** - * Props for the SwapWidgetProvider. + * Props accepted by {@link SwapWidgetProvider} — the inputs that configure the swap flow (token universe, network override, defaults). + * + * @public + * @category Type + * @section Swap */ export interface SwapProviderProps extends PropsWithChildren { - /** Full list of tokens available for swapping in the UI */ + /** Full list of tokens available for swapping in the UI. Filtered to the active network internally. */ tokens: AppkitUIToken[]; - /** Optional section configs for grouping tokens in the selector */ + /** Optional section configs for grouping tokens inside the `SwapTokenSelectModal`. */ tokenSections?: TokenSectionConfig[]; - /** Ticker of the token pre-selected for the source */ + /** Symbol of the token pre-selected as the source on first mount (e.g. `"TON"`). */ defaultFromSymbol?: string; - /** Ticker of the token pre-selected for the target */ + /** Symbol of the token pre-selected as the target on first mount. */ defaultToSymbol?: string; - /** Initial slippage in basis points (100 = 1%), defaults to 50 (0.5%) */ - /** Network to use for quote fetching. When omitted, uses the selected wallet's network. */ + /** Network used for quote fetching and balance reads. When omitted, falls back to the selected wallet's network via {@link useNetwork}. */ network?: Network; - /** Fiat currency symbol for price display, defaults to "$" */ + /** Fiat currency symbol displayed next to converted amounts. Defaults to `"$"`. */ fiatSymbol?: string; - /** Initial slippage in basis points (100 = 1%), defaults to 100 (1%) */ + /** Initial slippage tolerance in basis points (`100` = 1%). Defaults to `100`. */ defaultSlippage?: number; } +/** + * Provider that wires up the full swap state machine — debounces the entered amount, fetches the quote via {@link useSwapQuote}, reads source/target balances, validates the input, exposes the active {@link appkit:SwapProvider}, and offers `sendSwapTransaction` which builds the transaction with {@link useBuildSwapTransaction} and sends it (raising the low-balance warning when the outflow exceeds the user's TON balance). Children read everything through {@link useSwapContext}. + * + * @public + * @category Component + * @section Swap + */ export const SwapWidgetProvider: FC = ({ children, tokens, diff --git a/packages/appkit-react/src/features/swap/components/swap-widget-ui/swap-widget-ui.tsx b/packages/appkit-react/src/features/swap/components/swap-widget-ui/swap-widget-ui.tsx index 4a5ec13b2..2095d5cba 100644 --- a/packages/appkit-react/src/features/swap/components/swap-widget-ui/swap-widget-ui.tsx +++ b/packages/appkit-react/src/features/swap/components/swap-widget-ui/swap-widget-ui.tsx @@ -11,7 +11,6 @@ import type { FC, ComponentProps } from 'react'; import clsx from 'clsx'; import { useI18n } from '../../../settings/hooks/use-i18n'; -import { useSelectedWallet } from '../../../wallets'; import { SwapField } from '../swap-field'; import { SwapFlipButton } from '../swap-flip-button'; import { SwapInfo } from '../swap-info'; @@ -23,8 +22,22 @@ import type { SwapContextType } from '../swap-widget-provider'; import { ButtonWithConnect } from '../../../../components/shared/button-with-connect'; import { SettingsButton } from '../../../../components/shared/settings-button'; +/** + * Props accepted by {@link SwapWidgetUI} (and the `children` render-prop on {@link SwapWidget}). Combines the full {@link SwapContextType} with the standard `
          ` attributes forwarded to the wrapper element. + * + * @public + * @category Type + * @section Swap + */ export type SwapWidgetRenderProps = SwapContextType & ComponentProps<'div'>; +/** + * Default visual implementation of the swap widget — composes {@link SwapField} (source, then target), a {@link SwapFlipButton} between them, the submit button (auto-prompts wallet connect when no wallet is selected), the settings trigger that opens `SwapSettingsModal`, a `SwapTokenSelectModal` for picking source/target tokens, the {@link SwapInfo} summary, and a low-balance warning. Drives all state from the swap context props it receives — pair with {@link SwapWidgetProvider}, or use {@link SwapWidget} which mounts both. + * + * @public + * @category Component + * @section Swap + */ export const SwapWidgetUI: FC = ({ fromToken, toToken, @@ -61,9 +74,6 @@ export const SwapWidgetUI: FC = ({ className, ...props }) => { - const [wallet] = useSelectedWallet(); - const isWalletConnected = wallet !== null; - const { t } = useI18n(); const [activeField, setActiveField] = useState<'from' | 'to' | null>(null); @@ -96,7 +106,6 @@ export const SwapWidgetUI: FC = ({ isBalanceLoading={isFromBalanceLoading} onMaxClick={onMaxClick} onTokenSelectorClick={() => setActiveField('from')} - isWalletConnected={isWalletConnected} />
          @@ -113,7 +122,6 @@ export const SwapWidgetUI: FC = ({ isBalanceLoading={isToBalanceLoading} onTokenSelectorClick={() => setActiveField('to')} loading={isQuoteLoading} - isWalletConnected={isWalletConnected} />
          diff --git a/packages/appkit-react/src/features/swap/components/swap-widget/swap-widget.tsx b/packages/appkit-react/src/features/swap/components/swap-widget/swap-widget.tsx index b9a2da12d..99581e78f 100644 --- a/packages/appkit-react/src/features/swap/components/swap-widget/swap-widget.tsx +++ b/packages/appkit-react/src/features/swap/components/swap-widget/swap-widget.tsx @@ -14,15 +14,14 @@ import { SwapWidgetProvider, useSwapContext } from '../swap-widget-provider'; import type { SwapProviderProps } from '../swap-widget-provider'; /** - * Props for the SwapWidget component. - * Inherits all configuration from SwapProviderProps. + * Props accepted by {@link SwapWidget} — extend {@link SwapProviderProps} (swap configuration: tokens, network, defaults) with the standard `
          ` attributes and an optional render-prop override. + * + * @public + * @category Type + * @section Swap */ export interface SwapWidgetProps extends Omit, Omit, 'children'> { - /** - * Custom render function. - * When provided, it replaces the default widget UI and gives full control over the rendering. - * Accesses all state and actions from the swap context. - */ + /** Optional render-prop receiving the full swap context plus the forwarded `
          ` props. When supplied it replaces the default {@link SwapWidgetUI}. */ children?: (props: SwapWidgetRenderProps) => ReactNode; } @@ -39,11 +38,13 @@ const SwapWidgetContent: FC< }; /** - * A high-level component that provides a complete swap interface. + * Drop-in swap UI that walks the user through picking the source/target tokens, entering an amount, reviewing the quote (rate, min-received, slippage, provider), and confirming the swap — which builds the transaction via {@link useBuildSwapTransaction} and dispatches it through the standard send flow. Internally mounts a {@link SwapWidgetProvider} so the rendered UI (default {@link SwapWidgetUI} or a custom `children` render-prop) can read state through {@link useSwapContext}. + * + * @sample docs/examples/src/appkit/components/swap#SWAP_WIDGET * - * It manages the token selection, quote fetching, and transaction building - * for swaps between TON and Jettons. It can be used as a standalone widget - * with default UI or customized using a render function. + * @public + * @category Component + * @section Swap */ export const SwapWidget: FC = ({ children, diff --git a/packages/appkit-react/src/features/swap/hooks/use-build-swap-transaction.ts b/packages/appkit-react/src/features/swap/hooks/use-build-swap-transaction.ts index 9b2138f4d..c1371d0e1 100644 --- a/packages/appkit-react/src/features/swap/hooks/use-build-swap-transaction.ts +++ b/packages/appkit-react/src/features/swap/hooks/use-build-swap-transaction.ts @@ -20,8 +20,22 @@ import type { import { useAppKit } from '../../settings'; import { useMutation } from '../../../libs/query'; +/** + * Parameters accepted by {@link useBuildSwapTransaction} — TanStack Query mutation options. + * + * @public + * @category Type + * @section Swap + */ export type UseBuildSwapTransactionParameters = BuildSwapTransactionMutationOptions; +/** + * Return type of {@link useBuildSwapTransaction} — TanStack Query mutation result. + * + * @public + * @category Type + * @section Swap + */ export type UseBuildSwapTransactionReturnType = UseMutationResult< BuildSwapTransactionData, BuildSwapTransactionErrorType, @@ -30,7 +44,15 @@ export type UseBuildSwapTransactionReturnType = UseMutationRe >; /** - * Hook to build a swap transaction from a previously fetched quote. + * Build a swap {@link appkit:TransactionRequest} from a {@link appkit:SwapQuote} (obtained via {@link useSwapQuote}) without sending it — lets the UI inspect, batch, or pass the request to {@link useSendTransaction} separately. Call `mutate(params)` where `params` matches {@link appkit:BuildSwapTransactionOptions} (quote, user address, optional slippage/deadline overrides). The resulting `TransactionRequest` is in `data` once the mutation resolves. + * + * @param parameters - {@link UseBuildSwapTransactionParameters} TanStack Query mutation overrides. + * @expand parameters + * @returns Mutation result for the build call. + * + * @public + * @category Hook + * @section Swap */ export const useBuildSwapTransaction = ( parameters?: UseBuildSwapTransactionParameters, diff --git a/packages/appkit-react/src/features/swap/hooks/use-swap-provider.ts b/packages/appkit-react/src/features/swap/hooks/use-swap-provider.ts index f409bce2d..f2dbf51d1 100644 --- a/packages/appkit-react/src/features/swap/hooks/use-swap-provider.ts +++ b/packages/appkit-react/src/features/swap/hooks/use-swap-provider.ts @@ -12,11 +12,23 @@ import type { GetSwapProviderReturnType } from '@ton/appkit'; import { useAppKit } from '../../settings/hooks/use-app-kit'; +/** + * Return type of {@link useSwapProvider} — `[provider, setProviderId]` tuple. `provider` is the default `SwapProviderInterface` (or `undefined` when none is registered). `setProviderId` calls {@link appkit:setDefaultSwapProvider} and emits `provider:default-changed`, which {@link appkit:watchSwapProviders} picks up. + * + * @public + * @category Type + * @section Swap + */ export type UseSwapProviderReturnType = readonly [GetSwapProviderReturnType | undefined, (providerId: string) => void]; /** - * Hook to get and set the currently selected swap provider. - * Mirrors the tuple shape of `useSelectedWallet`. + * Read and switch the default swap provider — subscribes to {@link appkit:watchSwapProviders} and re-reads via {@link appkit:getSwapProvider}. Returns a `useState`-style tuple. The read swallows the throw from {@link appkit:getSwapProvider} (which throws when no provider matches — or when no id is passed and no default has been registered) and yields `undefined` instead. + * + * @returns Tuple `[provider, setProviderId]`. + * + * @public + * @category Hook + * @section Swap */ export const useSwapProvider = (): UseSwapProviderReturnType => { const appKit = useAppKit(); diff --git a/packages/appkit-react/src/features/swap/hooks/use-swap-providers.ts b/packages/appkit-react/src/features/swap/hooks/use-swap-providers.ts index 97d9a8ec9..35a976219 100644 --- a/packages/appkit-react/src/features/swap/hooks/use-swap-providers.ts +++ b/packages/appkit-react/src/features/swap/hooks/use-swap-providers.ts @@ -12,10 +12,23 @@ import type { GetSwapProvidersReturnType } from '@ton/appkit'; import { useAppKit } from '../../settings/hooks/use-app-kit'; +/** + * Return type of {@link useSwapProviders} — array of every `SwapProviderInterface` currently registered on the AppKit instance. + * + * @public + * @category Type + * @section Swap + */ export type UseSwapProvidersReturnType = GetSwapProvidersReturnType; /** - * Hook to get all registered swap providers. + * List every swap provider registered on the AppKit instance (both those passed via {@link appkit:AppKitConfig}'s `providers` and those added later through {@link appkit:registerProvider}). Subscribes to {@link appkit:watchSwapProviders} and re-reads via {@link appkit:getSwapProviders} so the array stays in sync. + * + * @returns Array of registered swap providers. + * + * @public + * @category Hook + * @section Swap */ export const useSwapProviders = (): UseSwapProvidersReturnType => { const appKit = useAppKit(); diff --git a/packages/appkit-react/src/features/swap/hooks/use-swap-quote.ts b/packages/appkit-react/src/features/swap/hooks/use-swap-quote.ts index 54cdb5971..fce5b35eb 100644 --- a/packages/appkit-react/src/features/swap/hooks/use-swap-quote.ts +++ b/packages/appkit-react/src/features/swap/hooks/use-swap-quote.ts @@ -16,15 +16,37 @@ import { useQuery } from '../../../libs/query'; import type { UseQueryReturnType } from '../../../libs/query'; import { useNetwork } from '../../network'; +/** + * Parameters accepted by {@link useSwapQuote} — TanStack Query options (`select`, `enabled`, `staleTime`, …) plus the {@link appkit:SwapQuoteParams} fields (source/target tokens, amount, `isReverseSwap` flag) and an optional `providerId` / network override. + * + * @public + * @category Type + * @section Swap + */ export type UseSwapQuoteParameters = GetSwapQuoteQueryConfig; +/** + * Return type of {@link useSwapQuote} — TanStack Query result carrying `data` ({@link appkit:SwapQuote}), `isLoading`, `error` and the standard companions. + * + * @public + * @category Type + * @section Swap + */ export type UseSwapQuoteReturnType = UseQueryReturnType< selectData, GetSwapQuoteErrorType >; /** - * Hook to get a swap quote for the given token pair and amount. + * Quote a swap — given source/target tokens and an amount, returns the rate, expected output and the provider-specific metadata required to feed {@link useBuildSwapTransaction}. `data` is the {@link appkit:SwapQuote} payload. The `network` field defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. + * + * @param parameters - {@link UseSwapQuoteParameters} Source and target tokens, amount, optional network/provider override, and TanStack Query overrides. + * @expand parameters + * @returns TanStack Query result for the swap quote. + * + * @public + * @category Hook + * @section Swap */ export const useSwapQuote = ( parameters: UseSwapQuoteParameters = {}, diff --git a/packages/appkit-react/src/features/transaction/components/transaction-progress/transaction-progress.tsx b/packages/appkit-react/src/features/transaction/components/transaction-progress/transaction-progress.tsx index 8cc866cf1..51b284727 100644 --- a/packages/appkit-react/src/features/transaction/components/transaction-progress/transaction-progress.tsx +++ b/packages/appkit-react/src/features/transaction/components/transaction-progress/transaction-progress.tsx @@ -27,7 +27,7 @@ export interface TransactionProgressRenderProps extends TransactionProgressConte } export interface TransactionProgressProps extends Omit, 'children'> { - /** BOC of the transaction to strictly track status */ + /** BoC of the transaction to strictly track status */ boc: string; /** Render props function for full control over rendering */ children?: (props: TransactionProgressRenderProps) => ReactNode; diff --git a/packages/appkit-react/src/features/transaction/components/transaction-provider/send-provider.tsx b/packages/appkit-react/src/features/transaction/components/transaction-provider/send-provider.tsx index cd314777e..53553cc54 100644 --- a/packages/appkit-react/src/features/transaction/components/transaction-provider/send-provider.tsx +++ b/packages/appkit-react/src/features/transaction/components/transaction-provider/send-provider.tsx @@ -40,13 +40,13 @@ export const useSendContext = () => { }; export interface SendProviderProps extends PropsWithChildren { - /** The transaction request parameters */ + /** Transaction request (or a sync/async producer of one) the provider hands to {@link sendTransaction} when triggered. */ request: SendRequest; - /** Callback when an error occurs */ + /** Called when the wallet rejects the request or the send fails. Receives the raised `Error`. */ onError?: (error: Error) => void; - /** Callback when the transaction is successful */ + /** Called once the transaction is broadcast. Receives the wallet's {@link SendTransactionReturnType} (BoC + normalized hash). */ onSuccess?: (response: SendTransactionReturnType) => void; - /** Disable the button/interaction */ + /** When true, descendant trigger components disable themselves and ignore clicks. */ disabled?: boolean; } diff --git a/packages/appkit-react/src/features/transaction/components/transaction/send.tsx b/packages/appkit-react/src/features/transaction/components/transaction/send.tsx index 542923deb..430978e50 100644 --- a/packages/appkit-react/src/features/transaction/components/transaction/send.tsx +++ b/packages/appkit-react/src/features/transaction/components/transaction/send.tsx @@ -29,15 +29,15 @@ export type SendRequest = | (() => Promise); export interface SendProps extends Omit { - /** The transaction request parameters */ + /** Transaction request (or a sync/async producer of one) the button hands to {@link sendTransaction} on click. */ request: SendRequest; - /** Callback when an error occurs */ + /** Called when the wallet rejects the request or the send fails. Receives the raised `Error`. */ onError?: (error: Error) => void; - /** Callback when the transaction is successful */ + /** Called once the transaction is broadcast. Receives the wallet's {@link SendTransactionReturnType} (BoC + normalized hash). */ onSuccess?: (response: SendTransactionReturnType) => void; - /** Custom button text */ + /** Override the button label. Defaults to "Send". */ text?: ReactNode; - /** Custom render function */ + /** Custom render function — replaces the default button with the caller's UI. Receives the current send state and click handler via {@link SendRenderProps}. */ children?: (props: SendRenderProps) => ReactNode; } diff --git a/packages/appkit-react/src/features/transaction/hooks/use-send-transaction.ts b/packages/appkit-react/src/features/transaction/hooks/use-send-transaction.ts index b8aca2b68..d560f9201 100644 --- a/packages/appkit-react/src/features/transaction/hooks/use-send-transaction.ts +++ b/packages/appkit-react/src/features/transaction/hooks/use-send-transaction.ts @@ -21,8 +21,22 @@ import { useMutation } from '../../../libs/query'; import type { UseMutationReturnType } from '../../../libs/query'; import { useAppKit } from '../../settings'; +/** + * Parameters accepted by {@link useSendTransaction} — TanStack Query mutation options. + * + * @public + * @category Type + * @section Transactions + */ export type UseSendTransactionParameters = SendTransactionOptions; +/** + * Return type of {@link useSendTransaction} — TanStack Query mutation result. + * + * @public + * @category Type + * @section Transactions + */ export type UseSendTransactionReturnType = UseMutationReturnType< SendTransactionData, SendTransactionErrorType, @@ -35,6 +49,17 @@ export type UseSendTransactionReturnType = UseMutationReturnT MutateFunction >; +/** + * Hand a pre-built {@link appkit:TransactionRequest} to the selected wallet for signing and broadcast — typically the second step after a `buildX` / `createX` action (e.g. {@link useBuildSwapTransaction}, {@link useBuildStakeTransaction}) produces the request. Call `mutate(request)`. On success, `data` carries the BoC and normalized hash of the broadcast transaction. Throws `Error('Wallet not connected')` if no wallet is currently selected — TanStack Query surfaces it via the mutation's `error`. + * + * @param parameters - {@link UseSendTransactionParameters} TanStack Query mutation overrides. + * @expand parameters + * @returns Mutation result for the send call. + * + * @public + * @category Hook + * @section Transactions + */ export const useSendTransaction = ( parameters: UseSendTransactionParameters = {}, ): UseSendTransactionReturnType => { diff --git a/packages/appkit-react/src/features/transaction/hooks/use-transaction-status.ts b/packages/appkit-react/src/features/transaction/hooks/use-transaction-status.ts index a1b4d5d65..799041404 100644 --- a/packages/appkit-react/src/features/transaction/hooks/use-transaction-status.ts +++ b/packages/appkit-react/src/features/transaction/hooks/use-transaction-status.ts @@ -19,33 +19,38 @@ import type { UseQueryReturnType } from '../../../libs/query'; import { useAppKit } from '../../settings'; import { useNetwork } from '../../network'; +/** + * Parameters accepted by {@link useTransactionStatus} — `boc` xor `normalizedHash` plus optional network and TanStack Query overrides. Pair with `query.refetchInterval` to poll until the transaction completes. + * + * @public + * @category Type + * @section Transactions + */ export type UseTransactionStatusParameters = GetTransactionStatusParameters & GetTransactionStatusQueryConfig; +/** + * Return type of {@link useTransactionStatus} — TanStack Query result for the status read. + * + * @public + * @category Type + * @section Transactions + */ export type UseTransactionStatusReturnType = UseQueryReturnType< selectData, GetTransactionStatusErrorType >; /** - * Hook to get the status of a transaction trace by BOC. - * - * This hook polls the toncenter API to track the progress of a transaction trace. - * It is useful for tracking complex operations like swaps or multi-step flows. + * Poll the status of a sent transaction by its BoC or normalized hash. In TON a single external message triggers a tree of internal messages, so the transaction is `'completed'` only once the entire trace finishes — pair with `refetchInterval` to keep polling until `data.status` is `'completed'` or `'failed'`. Pass either `boc` or `normalizedHash` (not both). The underlying action throws `Error('Either boc or normalizedHash must be provided')` when neither is supplied — TanStack Query surfaces it via the query's `error`. * - * @example - * ```ts - * const { data: status } = useTransactionStatus({ - * boc: 'te6cc...', - * query: { - * refetchInterval: 2000, // Poll every 2 seconds - * } - * }); + * @param parameters - {@link UseTransactionStatusParameters} `boc` xor `normalizedHash`, optional network and TanStack Query overrides. + * @expand parameters + * @returns TanStack Query result for the status read. * - * if (status?.status === 'pending') { - * console.log(`Progress: ${status.completedMessages}/${status.totalMessages}`); - * } - * ``` + * @public + * @category Hook + * @section Transactions */ export const useTransactionStatus = ( parameters: UseTransactionStatusParameters, diff --git a/packages/appkit-react/src/features/transaction/hooks/use-transfer-ton.ts b/packages/appkit-react/src/features/transaction/hooks/use-transfer-ton.ts index d1d65f1ec..a76f40a8a 100644 --- a/packages/appkit-react/src/features/transaction/hooks/use-transfer-ton.ts +++ b/packages/appkit-react/src/features/transaction/hooks/use-transfer-ton.ts @@ -21,8 +21,22 @@ import { useMutation } from '../../../libs/query'; import type { UseMutationReturnType } from '../../../libs/query'; import { useAppKit } from '../../settings'; +/** + * Parameters accepted by {@link useTransferTon} — TanStack Query mutation options. + * + * @public + * @category Type + * @section Transactions + */ export type UseTransferTonParameters = TransferTonOptions; +/** + * Return type of {@link useTransferTon} — TanStack Query mutation result. + * + * @public + * @category Type + * @section Transactions + */ export type UseTransferTonReturnType = UseMutationReturnType< TransferTonData, TransferTonErrorType, @@ -35,6 +49,17 @@ export type UseTransferTonReturnType = UseMutationReturnType< MutateFunction >; +/** + * Send TON from the selected wallet in one step — builds the transfer message, hands it to the wallet for signing and broadcasts it. Call `mutate` with a `recipientAddress`, an `amount` (in TON as a human-readable decimal, converted to nano-TON internally) and any of the optional `comment` / `payload` / `stateInit` fields. On success, `data` carries the BoC and normalized hash of the broadcast transaction — pair with {@link useTransactionStatus} to poll the trace to completion. Throws `Error('Wallet not connected')` if no wallet is currently selected — TanStack Query surfaces it via the mutation's `error`. + * + * @param parameters - {@link UseTransferTonParameters} TanStack Query mutation overrides. + * @expand parameters + * @returns Mutation result for the transfer call. + * + * @public + * @category Hook + * @section Transactions + */ export const useTransferTon = ( parameters: UseTransferTonParameters = {}, ): UseTransferTonReturnType => { diff --git a/packages/appkit-react/src/features/transaction/hooks/use-watch-transactions-by-address.ts b/packages/appkit-react/src/features/transaction/hooks/use-watch-transactions-by-address.ts index 06886c82d..37d8293db 100644 --- a/packages/appkit-react/src/features/transaction/hooks/use-watch-transactions-by-address.ts +++ b/packages/appkit-react/src/features/transaction/hooks/use-watch-transactions-by-address.ts @@ -12,10 +12,26 @@ import type { WatchTransactionsByAddressOptions, TransactionsUpdate } from '@ton import { useAppKit } from '../../settings'; +/** + * Parameters accepted by {@link useWatchTransactionsByAddress} — same fields as {@link appkit:WatchTransactionsByAddressOptions}, all optional so callers can render the hook before the address is known. + * + * @public + * @category Type + * @section Transactions + */ export type UseWatchTransactionsByAddressParameters = Partial; /** - * Hook to watch transactions for a specific address in real-time. + * Subscribe to incoming-transaction events for an arbitrary address (use {@link useWatchTransactions} for the selected wallet). Requires a streaming provider registered for the network — the hook exits silently with a console warning when none is configured. + * + * @param parameters - {@link UseWatchTransactionsByAddressParameters} Address, update callback and optional network override. + * @expand parameters + * + * @sample docs/examples/src/appkit/hooks/transaction#USE_WATCH_TRANSACTIONS_BY_ADDRESS + * + * @public + * @category Hook + * @section Transactions */ export const useWatchTransactionsByAddress = (parameters: UseWatchTransactionsByAddressParameters): void => { const { address, network } = parameters; diff --git a/packages/appkit-react/src/features/transaction/hooks/use-watch-transactions.ts b/packages/appkit-react/src/features/transaction/hooks/use-watch-transactions.ts index 4e1fa5a63..146548cc5 100644 --- a/packages/appkit-react/src/features/transaction/hooks/use-watch-transactions.ts +++ b/packages/appkit-react/src/features/transaction/hooks/use-watch-transactions.ts @@ -12,12 +12,29 @@ import { useAddress } from '../../wallets/hooks/use-address'; import { useNetwork } from '../../network/hooks/use-network'; import { useWatchTransactionsByAddress } from './use-watch-transactions-by-address'; +/** + * Parameters accepted by {@link useWatchTransactions}. + * + * @public + * @category Type + * @section Transactions + */ export interface UseWatchTransactionsParameters { + /** Callback fired on every transactions update from the streaming provider. */ onChange?: (update: TransactionsUpdate) => void; } /** - * Hook to watch transaction updates of the currently selected wallet in real-time. + * Subscribe to incoming-transaction events for the currently selected wallet (use {@link useWatchTransactionsByAddress} for a fixed address). Auto-rebinds when the user connects, switches or disconnects. Requires a streaming provider registered for the network — the hook exits silently with a console warning when none is configured. + * + * @param parameters - {@link UseWatchTransactionsParameters} Update callback. + * @expand parameters + * + * @sample docs/examples/src/appkit/hooks/transaction#USE_WATCH_TRANSACTIONS + * + * @public + * @category Hook + * @section Transactions */ export const useWatchTransactions = (parameters: UseWatchTransactionsParameters = {}): void => { const address = useAddress(); diff --git a/packages/appkit-react/src/features/wallets/hooks/use-address.ts b/packages/appkit-react/src/features/wallets/hooks/use-address.ts index f643f5239..8b44bd358 100644 --- a/packages/appkit-react/src/features/wallets/hooks/use-address.ts +++ b/packages/appkit-react/src/features/wallets/hooks/use-address.ts @@ -10,10 +10,23 @@ import { useMemo } from 'react'; import { useSelectedWallet } from './use-selected-wallet'; +/** + * Return type of {@link useAddress} — `undefined` when no wallet is selected. + * + * @public + * @category Type + * @section Wallets + */ export type UseAddressReturnType = string | undefined; /** - * Hook to get current wallet address + * Read the user-friendly address of the currently selected wallet. Updates when the selection changes. + * + * @returns Selected wallet's address, or `undefined` when none is selected. + * + * @public + * @category Hook + * @section Wallets */ export const useAddress = (): UseAddressReturnType => { const [wallet] = useSelectedWallet(); diff --git a/packages/appkit-react/src/features/wallets/hooks/use-connect.ts b/packages/appkit-react/src/features/wallets/hooks/use-connect.ts index 014bba94e..7c810f98a 100644 --- a/packages/appkit-react/src/features/wallets/hooks/use-connect.ts +++ b/packages/appkit-react/src/features/wallets/hooks/use-connect.ts @@ -14,8 +14,22 @@ import { useMutation } from '../../../libs/query'; import type { UseMutationReturnType } from '../../../libs/query'; import { useAppKit } from '../../settings'; +/** + * Parameters accepted by {@link useConnect} — TanStack Query mutation options (`onSuccess`, `onError`, `onMutate`, `retry`, …). + * + * @public + * @category Type + * @section Wallets + */ export type UseConnectParameters = ConnectOptions; +/** + * Return type of {@link useConnect} — TanStack Query mutation result with `mutate`/`mutateAsync` and the standard companions. + * + * @public + * @category Type + * @section Wallets + */ export type UseConnectReturnType = UseMutationReturnType< ConnectData, ConnectErrorType, @@ -28,6 +42,17 @@ export type UseConnectReturnType = UseMutationReturnType< MutateFunction >; +/** + * Open a registered connector's connection flow (e.g., the TonConnect modal) and await its completion. Call `mutate` from a Connect button with the `connectorId` of the connector to drive. Once the user finishes the flow the new wallet becomes available via {@link useSelectedWallet} / {@link useConnectedWallets}. Throws `Error('Connector with id "" not found')` when no connector with that id is registered — TanStack Query surfaces it via the mutation's `error`. + * + * @param parameters - {@link UseConnectParameters} TanStack Query mutation overrides. + * @expand parameters + * @returns Mutation result for the connect call. + * + * @public + * @category Hook + * @section Wallets + */ export const useConnect = ( parameters: UseConnectParameters = {}, ): UseConnectReturnType => { diff --git a/packages/appkit-react/src/features/wallets/hooks/use-connected-wallets.ts b/packages/appkit-react/src/features/wallets/hooks/use-connected-wallets.ts index b473d3093..1a9395f8c 100644 --- a/packages/appkit-react/src/features/wallets/hooks/use-connected-wallets.ts +++ b/packages/appkit-react/src/features/wallets/hooks/use-connected-wallets.ts @@ -12,8 +12,24 @@ import type { GetConnectedWalletsReturnType } from '@ton/appkit'; import { useAppKit } from '../../settings'; +/** + * Return type of {@link useConnectedWallets} — same shape as {@link appkit:GetConnectedWalletsReturnType}. + * + * @public + * @category Type + * @section Wallets + */ export type UseConnectedWalletsReturnType = GetConnectedWalletsReturnType; +/** + * Read the list of currently connected wallets across all registered connectors. Updates when a wallet connects or disconnects. + * + * @returns Read-only array of {@link appkit:WalletInterface}s. + * + * @public + * @category Hook + * @section Wallets + */ export const useConnectedWallets = (): UseConnectedWalletsReturnType => { const appKit = useAppKit(); diff --git a/packages/appkit-react/src/features/wallets/hooks/use-connector-by-id.ts b/packages/appkit-react/src/features/wallets/hooks/use-connector-by-id.ts index 3ebed506a..04e00f12c 100644 --- a/packages/appkit-react/src/features/wallets/hooks/use-connector-by-id.ts +++ b/packages/appkit-react/src/features/wallets/hooks/use-connector-by-id.ts @@ -12,6 +12,16 @@ import type { Connector } from '@ton/appkit'; import { useAppKit } from '../../settings'; +/** + * Look up a connector by its id and stay subscribed to its registration lifecycle — updates when a connector with that id is registered (via AppKit's constructor or {@link appkit:addConnector}) or unregistered. Returns the matching {@link appkit:Connector}, or `undefined` when none with that id is currently registered. Use {@link useConnectedWallets} if you want to react to wallet connect/disconnect events instead. + * + * @param id - ID of the connector to look up. + * @returns The matching {@link appkit:Connector}, or `undefined` if none with that id is registered. + * + * @public + * @category Hook + * @section Connectors + */ export const useConnectorById = (id: string): Connector | undefined => { const appKit = useAppKit(); diff --git a/packages/appkit-react/src/features/wallets/hooks/use-connectors.ts b/packages/appkit-react/src/features/wallets/hooks/use-connectors.ts index 803600732..3b6259d1e 100644 --- a/packages/appkit-react/src/features/wallets/hooks/use-connectors.ts +++ b/packages/appkit-react/src/features/wallets/hooks/use-connectors.ts @@ -12,8 +12,24 @@ import type { GetConnectorsReturnType } from '@ton/appkit'; import { useAppKit } from '../../settings'; +/** + * Return type of {@link useConnectors} — same shape as {@link appkit:GetConnectorsReturnType}. + * + * @public + * @category Type + * @section Connectors + */ export type UseConnectorsReturnType = GetConnectorsReturnType; +/** + * Read the list of connectors registered on this AppKit instance. Updates when a connector is registered or unregistered (use {@link useConnectedWallets} to react to wallet connect/disconnect events). + * + * @returns Read-only array of registered {@link appkit:Connector}s. + * + * @public + * @category Hook + * @section Connectors + */ export const useConnectors = (): UseConnectorsReturnType => { const appKit = useAppKit(); diff --git a/packages/appkit-react/src/features/wallets/hooks/use-disconnect.ts b/packages/appkit-react/src/features/wallets/hooks/use-disconnect.ts index 9bf022804..2b35cca86 100644 --- a/packages/appkit-react/src/features/wallets/hooks/use-disconnect.ts +++ b/packages/appkit-react/src/features/wallets/hooks/use-disconnect.ts @@ -16,8 +16,22 @@ import { useMutation } from '../../../libs/query'; import type { UseMutationReturnType } from '../../../libs/query'; import { useAppKit } from '../../settings'; +/** + * Parameters accepted by {@link useDisconnect} — TanStack Query mutation options. + * + * @public + * @category Type + * @section Wallets + */ export type UseDisconnectParameters = DisconnectOptions; +/** + * Return type of {@link useDisconnect} — TanStack Query mutation result. + * + * @public + * @category Type + * @section Wallets + */ export type UseDisconnectReturnType = UseMutationReturnType< DisconnectData, DisconnectErrorType, @@ -30,6 +44,17 @@ export type UseDisconnectReturnType = UseMutationReturnType< MutateFunction >; +/** + * Tear down the session on a registered connector, disconnecting whichever wallet it currently holds. Call `mutate` from a Log out / Disconnect button with the `connectorId` of the connector to tear down. Once it resolves the wallet drops out of {@link useSelectedWallet} / {@link useConnectedWallets}. Throws `Error('Connector with id "" not found')` when no connector with that id is registered — TanStack Query surfaces it via the mutation's `error`. + * + * @param parameters - {@link UseDisconnectParameters} TanStack Query mutation overrides. + * @expand parameters + * @returns Mutation result for the disconnect call. + * + * @public + * @category Hook + * @section Wallets + */ export const useDisconnect = ( parameters: UseDisconnectParameters = {}, ): UseDisconnectReturnType => { diff --git a/packages/appkit-react/src/features/wallets/hooks/use-selected-wallet.ts b/packages/appkit-react/src/features/wallets/hooks/use-selected-wallet.ts index 8e8c129c2..f715011a0 100644 --- a/packages/appkit-react/src/features/wallets/hooks/use-selected-wallet.ts +++ b/packages/appkit-react/src/features/wallets/hooks/use-selected-wallet.ts @@ -12,10 +12,23 @@ import type { GetSelectedWalletReturnType } from '@ton/appkit'; import { useAppKit } from '../../settings'; +/** + * Return type of {@link useSelectedWallet} — `[wallet, setWalletId]` tuple. `wallet` is the active {@link appkit:WalletInterface} (or `null`). `setWalletId` calls {@link appkit:setSelectedWalletId} and emits `wallets:selection-changed`. + * + * @public + * @category Type + * @section Wallets + */ export type UseSelectedWalletReturnType = readonly [GetSelectedWalletReturnType, (walletId: string | null) => void]; /** - * Hook to get the currently selected wallet + * Read and switch the wallet that AppKit treats as active — most action hooks ({@link useBalance}, {@link useSignText}, {@link useTransferTon}) target this wallet implicitly. Returns a `useState`-style tuple. + * + * @returns Tuple `[wallet, setWalletId]`. + * + * @public + * @category Hook + * @section Wallets */ export const useSelectedWallet = (): UseSelectedWalletReturnType => { const appKit = useAppKit(); diff --git a/packages/appkit-react/src/index.ts b/packages/appkit-react/src/index.ts index 25e44c48b..71bf0037b 100644 --- a/packages/appkit-react/src/index.ts +++ b/packages/appkit-react/src/index.ts @@ -8,6 +8,7 @@ export { AppKitProvider } from './providers/app-kit-provider'; export { I18nProvider } from './providers/i18n-provider'; +export type { I18nContextType, I18nProviderProps } from './providers/i18n-provider'; export * from '@ton/appkit'; diff --git a/packages/appkit-react/src/providers/app-kit-provider.tsx b/packages/appkit-react/src/providers/app-kit-provider.tsx index 82d859195..7ef6c6136 100644 --- a/packages/appkit-react/src/providers/app-kit-provider.tsx +++ b/packages/appkit-react/src/providers/app-kit-provider.tsx @@ -15,10 +15,27 @@ import { TonConnectBridge } from '../tonconnect/tonconnect-bridge'; export const AppKitContext = createContext(undefined); +/** + * Props accepted by {@link AppKitProvider}. + * + * @public + * @category Type + * @section Providers + */ export interface AppKitProviderProps extends PropsWithChildren { + /** Runtime instance constructed at app startup. Shared across every appkit-react hook and component. */ appKit: AppKit; } +/** + * Top-level React provider that wires AppKit, the TonConnect bridge and i18n into the component tree — wrap your app once near the root so descendant hooks ({@link useAppKit}, {@link useBalance}, …) and components can resolve their context. + * + * @sample docs/examples/src/appkit/components/providers#APP_KIT_PROVIDER + * + * @public + * @category Component + * @section Providers + */ export const AppKitProvider: FC = ({ appKit, children }) => { return ( diff --git a/packages/appkit-react/src/providers/i18n-provider.tsx b/packages/appkit-react/src/providers/i18n-provider.tsx index 3b8c6fdb6..1d25011c8 100644 --- a/packages/appkit-react/src/providers/i18n-provider.tsx +++ b/packages/appkit-react/src/providers/i18n-provider.tsx @@ -12,20 +12,49 @@ import { createContext, useState, useRef, useEffect } from 'react'; import type { Dict, I18n } from '../libs/i18n'; import { i18n, defaultLanguage } from '../libs/i18n'; +/** + * Shape returned by {@link useI18n} — current locale, translation function and helpers to switch locales or merge new dictionaries at runtime. + * + * @public + * @category Type + * @section Providers + */ export interface I18nContextType { + /** Currently active locale code (e.g., `"en"`, `"ru"`). */ activeLocale: string; + /** Translation function — accepts a key plus interpolation values and returns the localized string. */ t: I18n['t']; + /** Switch to a new locale. Pass an optional `dict` to install translations alongside the switch. */ locale: (lang: string, dict?: Dict) => void; + /** Merge a translation dictionary for `lang` without changing the active locale. */ addDict: (lang: string, dict: Dict) => void; } export const I18nContext = createContext(null); +/** + * Props accepted by {@link I18nProvider}. + * + * @public + * @category Type + * @section Providers + */ export interface I18nProviderProps extends PropsWithChildren { + /** Initial locale code. Defaults to the i18n library's default when omitted. */ locale?: string; + /** Translation dictionaries keyed by locale. Loaded into the underlying i18n instance on mount. */ lngDicts?: Record; } +/** + * React provider that mounts the i18n context for {@link useI18n} and child components — already wrapped by {@link AppKitProvider}, so apps usually only render it directly when they need to override the locale or dictionaries. + * + * @sample docs/examples/src/appkit/components/providers#I18N_PROVIDER + * + * @public + * @category Component + * @section Providers + */ export const I18nProvider = ({ children, locale, lngDicts }: I18nProviderProps) => { const activeLocaleRef = useRef(locale || defaultLanguage); const [, setTick] = useState(0); diff --git a/packages/appkit-react/src/types/appkit-ui-token.ts b/packages/appkit-react/src/types/appkit-ui-token.ts index 2b866109b..de9c6dd26 100644 --- a/packages/appkit-react/src/types/appkit-ui-token.ts +++ b/packages/appkit-react/src/types/appkit-ui-token.ts @@ -8,21 +8,28 @@ import type { Network } from '@ton/appkit'; +/** + * UI-side token descriptor consumed by appkit-react widgets ({@link SwapWidget}, {@link SwapField}, currency selectors, etc.) — identifies the token in the picker UI and carries display + on-chain fields the widget needs to render and quote. + * + * @public + * @category Type + * @section Shared + */ export interface AppkitUIToken { - /** Unique identifier for the token, used for section grouping */ + /** Stable id used for picker selection state and section grouping. */ id: string; - /** Token symbol, e.g. "TON" */ + /** Ticker symbol shown in the picker and selector chip (e.g., `"TON"`, `"USDT"`). */ symbol: string; - /** Full token name, e.g. "Toncoin" */ + /** Full token name shown in the picker (e.g., `"Toncoin"`). */ name: string; - /** Number of decimals for the token */ + /** Number of decimal places used to format raw amounts. */ decimals: number; - /** Jetton contract address (use "ton" for TON) */ + /** Token contract address. Pass `'ton'` for native TON; otherwise the jetton master's user-friendly address. */ address: string; - /** Optional token logo */ + /** Optional URL of the token logo shown in the picker and selector chip. */ logo?: string; - /** Optional exchange rate: 1 token = rate fiat units (used for fiat value display) */ + /** Optional fiat exchange rate (`1 token = rate fiat units`). Used by widgets to render fiat conversions next to amounts. */ rate?: string; - /** Network the token belongs to. */ + /** {@link appkit:Network} the token lives on. Widgets filter their token universe by the active network. */ network: Network; } diff --git a/packages/appkit-react/src/utils/map-defi-error.ts b/packages/appkit-react/src/utils/map-defi-error.ts index f46fec947..28989a754 100644 --- a/packages/appkit-react/src/utils/map-defi-error.ts +++ b/packages/appkit-react/src/utils/map-defi-error.ts @@ -10,7 +10,7 @@ import { DefiError, DefiErrorCode } from '@ton/appkit'; /** * Map a thrown error to an i18n key from the `defi.*` namespace. - * Returns `null` when the error isn't a {@link DefiError} or the code isn't recognised — + * Returns `null` when the error isn't a {@link appkit:DefiError} or the code isn't recognised — * callers should decide on their own fallback (usually a domain-specific key). */ export const mapDefiError = (error: unknown): string | null => { diff --git a/packages/appkit/README.md b/packages/appkit/README.md index a309e5553..cb67bcd35 100644 --- a/packages/appkit/README.md +++ b/packages/appkit/README.md @@ -1,7 +1,7 @@ # TonAppKit @@ -72,7 +72,7 @@ const appKit = new AppKit({ ```ts const balance = await getBalance(appKit); if (balance) { - console.log('Balance:', balance.toString()); + console.log('Balance:', balance); } ``` diff --git a/packages/appkit/docs/actions.md b/packages/appkit/docs/actions.md index 5c2280b02..d404e178b 100644 --- a/packages/appkit/docs/actions.md +++ b/packages/appkit/docs/actions.md @@ -1,7 +1,7 @@ # Actions @@ -17,7 +17,7 @@ Get the TON balance of the currently selected wallet. ```ts const balance = await getBalance(appKit); if (balance) { - console.log('Balance:', balance.toString()); + console.log('Balance:', balance); } ``` @@ -27,9 +27,9 @@ Fetch the TON balance of a specific address. ```ts const balanceByAddress = await getBalanceByAddress(appKit, { - address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', // Zero Address + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', }); -console.log('Balance by address:', balanceByAddress.toString()); +console.log('Balance by address:', balanceByAddress); ``` ### `watchBalance` @@ -78,7 +78,7 @@ await connect(appKit, { Add a wallet connector to AppKit (e.g., TonConnect). ```ts -const stopWatching = addConnector( +const unregister = addConnector( appKit, createTonConnectConnector({ tonConnectOptions: { @@ -87,7 +87,7 @@ const stopWatching = addConnector( }), ); -// Later: stopWatching(); +// Later: unregister(); ``` ### `disconnect` @@ -167,7 +167,7 @@ if (!response) { return; } console.log('Jettons:', response.jettons.length); -response.jettons.forEach((j) => console.log(`- ${j.info.name}: ${j.balance.toString()}`)); +response.jettons.forEach((j) => console.log(`- ${j.info.name}: ${j.balance}`)); ``` ### `getJettonsByAddress` @@ -185,7 +185,7 @@ const response = await getJettonsByAddress(appKit, { address: selectedWallet.getAddress(), }); console.log('Jettons by Address:', response.jettons.length); -response.jettons.forEach((j) => console.log(`- ${j.info.name}: ${j.balance.toString()}`)); +response.jettons.forEach((j) => console.log(`- ${j.info.name}: ${j.balance}`)); ``` ### `getJettonBalance` @@ -204,7 +204,7 @@ const balance = await getJettonBalance(appKit, { ownerAddress: selectedWallet.getAddress(), jettonDecimals: 6, }); -console.log('Jetton Balance:', balance.toString()); +console.log('Jetton Balance:', balance); ``` ### `getJettonInfo` @@ -390,7 +390,7 @@ Get all NFTs owned by a specific address. ```ts const response = await getNftsByAddress(appKit, { - address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', // Zero Address + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', }); console.log('NFTs by address:', response.nfts.length); @@ -563,7 +563,7 @@ Sign a TON Cell with the connected wallet. Used for on-chain signature verificat ```ts const result = await signCell(appKit, { - cell: 'te6ccgEBAQEAAgAAGA==' as Base64String, // Example BOC + cell: 'te6ccgEBAQEAAgAAGA==' as Base64String, // Example BoC schema: 'transfer#abc123 amount:uint64 = Transfer', }); @@ -657,7 +657,7 @@ console.log('Swap Transaction:', transactionResponse); Get all available staking provider IDs. ```ts -const providers = await getStakingProviders(appKit); +const providers = getStakingProviders(appKit); console.log('Available Staking Providers:', providers); ``` @@ -725,7 +725,7 @@ console.log('Staked Balance:', balance); Create a TON transfer transaction request without sending it. ```ts -const tx = await createTransferTonTransaction(appKit, { +const tx = createTransferTonTransaction(appKit, { recipientAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', amount: '0.1', // 0.1 TON (human-readable format) comment: 'Draft transaction', diff --git a/packages/appkit/docs/connectors.md b/packages/appkit/docs/connectors.md index 0586da547..9c7fe9b93 100644 --- a/packages/appkit/docs/connectors.md +++ b/packages/appkit/docs/connectors.md @@ -1,7 +1,7 @@ # Connectors diff --git a/packages/appkit/docs/reference.md b/packages/appkit/docs/reference.md new file mode 100644 index 000000000..0e1b07d64 --- /dev/null +++ b/packages/appkit/docs/reference.md @@ -0,0 +1,4528 @@ + + +## Action + +### Balances + +#### getBalance + +Read the Toncoin balance of the currently selected wallet, returning `null` when no wallet is selected (use [`getBalanceByAddress`](#getbalancebyaddress) for an arbitrary address). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options` | [`GetBalanceOptions`](#getbalanceoptions) | Optional network override. | +| `options.network` | Network | Network to read the balance from. Defaults to the selected wallet's network. | + +Returns: Promise<GetBalanceReturnType> — Balance in TON as a human-readable decimal string, or `null` when no wallet is selected. + +**Example** + +```ts +const balance = await getBalance(appKit); +if (balance) { + console.log('Balance:', balance); +} +``` + +#### getBalanceByAddress + +Read the Toncoin balance of an arbitrary address — useful for wallets that aren't selected in AppKit (use [`getBalance`](#getbalance) for the selected wallet). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetBalanceByAddressOptions`](#getbalancebyaddressoptions) | Target address and optional network. | +| `options.address`\* | UserFriendlyAddress \| Address | Wallet address — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `options.network` | Network | Network to read the balance from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +Returns: Promise<GetBalanceByAddressReturnType> — Balance in TON as a human-readable decimal string. + +**Example** + +```ts +const balanceByAddress = await getBalanceByAddress(appKit, { + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', +}); +console.log('Balance by address:', balanceByAddress); +``` + +#### watchBalance + +Subscribe to Toncoin balance updates for the currently selected wallet, automatically rebinding whenever the selected wallet changes or the connected-wallets list updates (use [`watchBalanceByAddress`](#watchbalancebyaddress) for a fixed address). Requires a streaming provider registered for the network — call throws when none is configured. Use [`hasStreamingProvider`](#hasstreamingprovider) to check first. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`WatchBalanceOptions`](#watchbalanceoptions) | Update callback and optional network override. | +| `options.network` | Network | Network to watch on. Defaults to the selected wallet's network. | +| `options.onChange`\* | (update: BalanceUpdate) => void | Callback fired on every balance update from the streaming provider. | + +Returns: WatchBalanceReturnType — Unsubscribe function — call it to stop receiving updates. + +**Example** + +```ts +const unsubscribe = watchBalance(appKit, { + onChange: (update) => { + console.log('Balance updated:', update.balance); + }, +}); + +// Later: unsubscribe(); +``` + +#### watchBalanceByAddress + +Subscribe to Toncoin balance updates for an arbitrary address — useful for monitoring wallets that aren't selected in AppKit (use [`watchBalance`](#watchbalance) for the selected wallet). Requires a streaming provider registered for the network — call throws when none is configured. Use [`hasStreamingProvider`](#hasstreamingprovider) to check first. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`WatchBalanceByAddressOptions`](#watchbalancebyaddressoptions) | Target address, update callback and optional network override. | +| `options.address`\* | UserFriendlyAddress \| Address | Wallet address — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `options.network` | Network | Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `options.onChange`\* | (update: BalanceUpdate) => void | Callback fired on every balance update from the streaming provider. | + +Returns: WatchBalanceByAddressReturnType — Unsubscribe function — call it to stop receiving updates. + +**Example** + +```ts +const unsubscribe = watchBalanceByAddress(appKit, { + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + onChange: (update) => { + console.log('Balance by address updated:', update.balance); + }, +}); + +// Later: unsubscribe(); +``` + +### Client + +#### getApiClient + +Read the [`ApiClient`](#apiclient) configured for a specific [`Network`](#network) — throws when the network has no client registered. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetApiClientOptions`](#getapiclientoptions) | Network to look up. | +| `options.network`\* | Network | Network whose configured [`ApiClient`](#apiclient) should be returned. | + +Returns: GetApiClientReturnType — The configured [`ApiClient`](#apiclient) for the requested network. + +**Example** + +```ts +const apiClient = getApiClient(appKit, { + network: Network.mainnet(), +}); + +console.log('API Client:', apiClient); +``` + +### Connectors + +#### addConnector + +Register a wallet connector at runtime — equivalent to passing it via [`AppKitConfig`](#appkitconfig)'s `connectors` at construction, but available after AppKit is up. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `connector`\* | [`AddConnectorParameters`](#addconnectorparameters) | Connector instance or factory to register. | + +Returns: AddConnectorReturnType — Function that unregisters the connector when called. + +**Example** + +```ts +const unregister = addConnector( + appKit, + createTonConnectConnector({ + tonConnectOptions: { + manifestUrl: 'https://tonconnect-sdk-demo-dapp.vercel.app/tonconnect-manifest.json', + }, + }), +); + +// Later: unregister(); +``` + +#### connect + +Trigger the connection flow on a registered connector by id — drives it against AppKit's default network (set via [`setDefaultNetwork`](#setdefaultnetwork)). Throws when no connector with that id exists. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`ConnectParameters`](#connectparameters) | Connector to connect through. | +| `parameters.connectorId`\* | `string` | ID of the registered connector to drive the connection through (e.g., `'tonconnect'`). | + +Returns: Promise<ConnectReturnType> — Resolves once the connector's connect flow completes. If a wallet was successfully connected, it becomes available via [`getSelectedWallet`](#getselectedwallet). + +**Example** + +```ts +await connect(appKit, { + connectorId: 'tonconnect', +}); +``` + +#### createConnector + +Identity helper for typing a [`ConnectorFactory`](#connectorfactory) inline — returns the factory unchanged so authors get parameter inference without spelling the type out. + +| Parameter | Type | Description | +| --- | --- | --- | +| `factory`\* | [`ConnectorFactory`](#connectorfactory) | Factory to wrap. | + +Returns: ConnectorFactory — The same factory, typed as [`ConnectorFactory`](#connectorfactory). + +#### createTonConnectConnector + +Build a TonConnect-backed [`Connector`](#connector) for AppKit. Pass the result to [`AppKitConfig`](#appkitconfig)'s `connectors` or [`addConnector`](#addconnector). + +| Parameter | Type | Description | +| --- | --- | --- | +| `config`\* | [`TonConnectConnectorConfig`](#tonconnectconnectorconfig) | Connector ID, metadata override and TonConnect options or pre-built UI instance. | +| `config.id` | `string` | Connector ID. Defaults to [`TONCONNECT_DEFAULT_CONNECTOR_ID`](#tonconnect_default_connector_id) (`'tonconnect'`). Set this when you need to register multiple TonConnect-flavoured connectors side by side. | +| `config.metadata` | ConnectorMetadata | Display metadata override. Merged on top of TonConnect's default name and icon. | +| `config.tonConnectOptions` | `TonConnectUiCreateOptions` | Options forwarded to the underlying `TonConnectUI` constructor (manifest URL, etc.). Ignored when `tonConnectUI` is supplied. | +| `config.tonConnectUI` | `TonConnectUI` | Pre-built `TonConnectUI` instance to reuse. When set, the connector skips its own instantiation and `tonConnectOptions` is ignored. | + +Returns: ConnectorFactory — Factory function consumed by AppKit at registration time. + +**Example** + +```ts +// 1. Create TonConnectUI instance +const tonConnectUI = new TonConnectUI({ + manifestUrl: 'https://my-app.com/tonconnect-manifest.json', +}); + +// 2. Initialize AppKit +const appKit = new AppKit({ + networks: { + [Network.mainnet().chainId]: { + apiClient: { + url: 'https://toncenter.com', + key: 'your-key', + }, + }, + }, + connectors: [createTonConnectConnector({ tonConnectUI })], +}); +``` + +#### disconnect + +Tear down the session on a registered connector — disconnects the wallet currently connected through it, if any. Throws when no connector with that id exists. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`DisconnectParameters`](#disconnectparameters) | Connector to disconnect. | +| `parameters.connectorId`\* | `string` | ID of the registered connector whose wallet should be disconnected. | + +Returns: Promise<DisconnectReturnType> — Resolves once the connector tears down its session. + +**Example** + +```ts +await disconnect(appKit, { + connectorId: 'tonconnect', +}); +``` + +#### getConnectorById + +Look up a registered connector by its id. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetConnectorByIdOptions`](#getconnectorbyidoptions) | ID of the connector to find. | +| `options.id`\* | `string` | ID of the connector to look up. | + +Returns: GetConnectorByIdReturnType — The matching [`Connector`](#connector), or `undefined` if none with that id is registered. + +**Example** + +```ts +const connector = getConnectorById(appKit, { + id: 'tonconnect', +}); + +if (connector) { + console.log('Found connector:', connector.id); +} +``` + +#### getConnectors + +List every connector registered on this AppKit instance — both those passed via [`AppKitConfig`](#appkitconfig)'s `connectors` and those added later through [`addConnector`](#addconnector). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | + +Returns: GetConnectorsReturnType — Read-only array of registered [`Connector`](#connector)s. + +**Example** + +```ts +const connectors = getConnectors(appKit); +connectors.forEach((connector) => { + console.log('Connector:', connector.id); +}); +``` + +#### watchConnectorById + +Subscribe to register/unregister events for a connector with the given id — the callback fires when the connector is added or removed, so callers can react to its presence. Use [`watchConnectedWallets`](#watchconnectedwallets) if you want to react to wallet connect/disconnect events instead. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`WatchConnectorByIdParameters`](#watchconnectorbyidparameters) | Connector ID and update callback. | +| `parameters.id`\* | `string` | ID of the connector to watch. | +| `parameters.onChange`\* | (connector: Connector \| undefined) => void | Callback invoked when the connector with the watched id is registered or unregistered — receives the connector itself, or `undefined` when none is registered under that id. | + +Returns: WatchConnectorByIdReturnType — Unsubscribe function — call it to stop receiving updates. + +**Example** + +```ts +const unsubscribe = watchConnectorById(appKit, { + id: 'tonconnect', + onChange: (connector) => { + console.log('Connector updated:', connector); + }, +}); + +// Later: unsubscribe(); +``` + +#### watchConnectors + +Subscribe to changes in the registered-connectors list — the callback fires when a connector is added (via [`addConnector`](#addconnector) or AppKit's constructor) or removed, and receives the current list. Use [`watchConnectedWallets`](#watchconnectedwallets) if you want to react to wallet connect/disconnect events instead. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`WatchConnectorsParameters`](#watchconnectorsparameters) | Update callback. | +| `parameters.onChange`\* | (connectors: readonly Connector[]) => void | Callback invoked when the list of registered connectors changes — receives the current list. | + +Returns: WatchConnectorsReturnType — Unsubscribe function — call it to stop receiving updates. + +**Example** + +```ts +const unsubscribe = watchConnectors(appKit, { + onChange: (connectors) => { + console.log('Connectors updated:', connectors); + }, +}); + +// Later: unsubscribe(); +``` + +### Crypto Onramp + +#### createCryptoOnrampDeposit + +Create a crypto-onramp deposit from a quote previously obtained via [`getCryptoOnrampQuote`](#getcryptoonrampquote) — the returned [`CryptoOnrampDeposit`](#cryptoonrampdeposit) carries the address and amount the user must send on the source chain. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`CreateCryptoOnrampDepositOptions`](#createcryptoonrampdepositoptions) | Quote, refund address, and optional provider override. | +| `options.quote`\* | CryptoOnrampQuote<TQuoteMetadata = unknown> | Quote to execute the deposit against (contains recipientAddress and provider metadata) | +| `options.refundAddress`\* | `string` | Address to refund the crypto to in case of failure | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.providerId` | `string` | Provider to create the deposit through. Defaults to `quote.providerId`, then to the default provider. | + +Returns: CreateCryptoOnrampDepositReturnType — Deposit details the UI should show to the user (address, amount, optional `memo`/`expiresAt`). + +#### createLayerswapProvider + +Build a Layerswap-backed [`CryptoOnrampProvider`](#cryptoonrampprovider) for AppKit. Pass the result to [`AppKitConfig`](#appkitconfig)'s `providers` or [`registerProvider`](#registerprovider). + +| Parameter | Type | Description | +| --- | --- | --- | +| `config` | LayerswapProviderConfig | Optional [`LayerswapProviderConfig`](#layerswapproviderconfig). Defaults are filled in for any field left undefined. | + +Returns: ProviderFactory<LayerswapCryptoOnrampProvider>. + +#### createSwapsXyzProvider + +Build a swaps.xyz-backed [`CryptoOnrampProvider`](#cryptoonrampprovider) for AppKit. Pass the result to [`AppKitConfig`](#appkitconfig)'s `providers` or [`registerProvider`](#registerprovider). + +| Parameter | Type | Description | +| --- | --- | --- | +| `config`\* | [`SwapsXyzProviderConfig`](#swapsxyzproviderconfig) | Configuration carrying the required `apiKey` plus optional URL/sender overrides. | + +Returns: ProviderFactory<SwapsXyzCryptoOnrampProvider>. + +#### getCryptoOnrampProvider + +Get a registered crypto-onramp provider by id, or the default provider when no id is given. Throws when no provider matches — or when no id is passed and no default has been registered. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options` | [`GetCryptoOnrampProviderOptions`](#getcryptoonrampprovideroptions) | Optional provider id. | +| `options.id` | `string` | Provider ID to look up. When omitted, returns the registered default provider. | + +Returns: GetCryptoOnrampProviderReturnType — The matching [`CryptoOnrampProviderInterface`](#cryptoonrampproviderinterface). + +**Example** + +```ts +const provider = getCryptoOnrampProvider(appKit, { id: 'layerswap' }); +console.log('Crypto onramp provider:', provider.providerId); +``` + +#### getCryptoOnrampProviders + +List every crypto-onramp provider registered on this AppKit instance — both those passed via [`AppKitConfig`](#appkitconfig)'s `providers` and those added later through [`registerProvider`](#registerprovider). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | + +Returns: GetCryptoOnrampProvidersReturnType — Array of registered [`CryptoOnrampProviderInterface`](#cryptoonrampproviderinterface)s. + +**Example** + +```ts +const providers = getCryptoOnrampProviders(appKit); +console.log( + 'Registered crypto onramp providers:', + providers.map((p) => p.providerId), +); +``` + +#### getCryptoOnrampQuote + +Quote a crypto-to-TON onramp — given a source asset/chain and target TON asset, returns the rate, expected amount, and provider metadata needed to call [`createCryptoOnrampDeposit`](#createcryptoonrampdeposit). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetCryptoOnrampQuoteOptions`](#getcryptoonrampquoteoptions) | Source asset, target asset, amount and optional provider override. | +| `options.amount`\* | `string` | Amount to onramp (either source or target crypto, depending on isSourceAmount) | +| `options.sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | +| `options.sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | +| `options.targetCurrencyAddress`\* | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | +| `options.recipientAddress`\* | `string` | TON address that will receive the target crypto | +| `options.refundAddress` | `string` | Refund address for the source crypto | +| `options.isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.providerId` | `string` | Provider to quote against. Defaults to the registered default provider. | + +Returns: GetCryptoOnrampQuoteReturnType — Quote with pricing details and the provider metadata required to create a deposit. + +#### getCryptoOnrampStatus + +Read the current status of a crypto-onramp deposit by id — typically polled until the result is `'success'` or `'failed'`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetCryptoOnrampStatusOptions`](#getcryptoonrampstatusoptions) | Deposit id, originating provider id and optional provider override. | +| `options.depositId`\* | `string` | Deposit id | +| `options.providerId`\* | `string` | Identifier of the provider that issued this deposit | + +Returns: GetCryptoOnrampStatusReturnType — Current [`CryptoOnrampStatus`](#cryptoonrampstatus) of the deposit. + +#### watchCryptoOnrampProviders + +Subscribe to crypto-onramp provider lifecycle — fires `onChange` whenever a new provider is registered or the default crypto-onramp provider switches. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`WatchCryptoOnrampProvidersParameters`](#watchcryptoonrampprovidersparameters) | Update callback. | +| `parameters.onChange`\* | `() => void` | Callback fired whenever a crypto-onramp provider is registered or the default crypto-onramp provider changes. | + +Returns: WatchCryptoOnrampProvidersReturnType — Unsubscribe function — call it to stop receiving updates. + +### DeFi + +#### registerProvider + +Register a DeFi / onramp provider at runtime — equivalent to passing it via [`AppKitConfig`](#appkitconfig)'s `providers` at construction, but available after AppKit is up. AppKit emits `provider:registered`, picked up by domain-specific subscribers like [`watchSwapProviders`](#watchswapproviders) and [`watchCryptoOnrampProviders`](#watchcryptoonrampproviders). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `provider`\* | [`RegisterProviderOptions`](#registerprovideroptions) | Provider instance or factory to register. | + +Returns: `void`. + +**Example** + +```ts +registerProvider( + appKit, + createOmnistonProvider({ + defaultSlippageBps: 100, // 1% + }), +); +``` + +### Jettons + +#### createTransferJettonTransaction + +Build a jetton transfer [`TransactionRequest`](#transactionrequest) for the selected wallet without sending it — useful when the UI needs to inspect or batch transactions before signing. Throws `Error('Wallet not connected')` if no wallet is currently selected. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`CreateTransferJettonTransactionParameters`](#createtransferjettontransactionparameters) | Jetton, recipient, amount, decimals and optional comment. | +| `parameters.jettonAddress`\* | UserFriendlyAddress | Jetton master contract address being transferred. | +| `parameters.recipientAddress`\* | UserFriendlyAddress | Recipient who should receive the jettons. | +| `parameters.amount`\* | `string` | Amount in jetton units as a human-readable decimal string (e.g., `"1.5"`). | +| `parameters.jettonDecimals`\* | `number` | Decimals declared by the jetton master. Used to convert `amount` into raw smallest units. | +| `parameters.comment` | `string` | Optional human-readable comment attached to the transfer. | + +Returns: Promise<CreateTransferJettonTransactionReturnType> — Transaction request ready to pass to `sendTransaction`. + +**Example** + +```ts +const tx = await createTransferJettonTransaction(appKit, { + jettonAddress: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs', + recipientAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + amount: '100', // 100 USDT + comment: 'Hello Jetton', + jettonDecimals: 6, +}); +console.log('Transfer Transaction:', tx); +``` + +#### getJettonBalance + +Read a jetton balance for a given owner — derives the owner's jetton-wallet address from the master, then fetches and formats the balance using the supplied decimals. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetJettonBalanceOptions`](#getjettonbalanceoptions) | Jetton master, owner address, decimals and optional network override. | +| `options.jettonAddress`\* | UserFriendlyAddress | Jetton master contract address (the token, not the user's wallet for it). | +| `options.ownerAddress`\* | UserFriendlyAddress | Owner of the jetton wallet — typically the connected user's address. | +| `options.jettonDecimals`\* | `number` | Decimals declared by the jetton master. Used to format the raw balance into a human-readable string. | +| `options.network` | Network | Network to read the balance from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +Returns: Promise<GetJettonBalanceReturnType> — Balance as a human-readable decimal string in the jetton's units. + +**Example** + +```ts +const selectedWallet = getSelectedWallet(appKit); +if (!selectedWallet) { + console.log('No wallet selected'); + return; +} + +const balance = await getJettonBalance(appKit, { + jettonAddress: 'EQDBE420tTQIkoWcZ9pEOTKY63WVmwyIl3hH6yWl0r_h51Tl', + ownerAddress: selectedWallet.getAddress(), + jettonDecimals: 6, +}); +console.log('Jetton Balance:', balance); +``` + +#### getJettonInfo + +Fetch token metadata for a jetton master — name, symbol, decimals, image and description as reported by the indexer. Returns `null` when the indexer has no record for that master address. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetJettonInfoOptions`](#getjettoninfooptions) | Jetton master address and optional network override. | +| `options.address`\* | UserFriendlyAddress | Jetton master contract address whose metadata is being fetched. | +| `options.network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +Returns: Promise<GetJettonInfoReturnType> — Jetton metadata, or `null` if the indexer has no record. + +**Example** + +```ts +const info = await getJettonInfo(appKit, { + address: 'EQDBE420tTQIkoWcZ9pEOTKY63WVmwyIl3hH6yWl0r_h51Tl', +}); +console.log('Jetton Info:', info); +``` + +#### getJettonWalletAddress + +Derive the jetton-wallet address for a given owner — the per-owner contract that actually holds the jetton balance for `jettonAddress`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetJettonWalletAddressOptions`](#getjettonwalletaddressoptions) | Jetton master, owner address and optional network override. | +| `options.jettonAddress`\* | UserFriendlyAddress | Jetton master contract address. | +| `options.ownerAddress`\* | UserFriendlyAddress | Owner whose jetton wallet should be derived. | +| `options.network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +Returns: Promise<GetJettonWalletAddressReturnType> — User-friendly address of the owner's jetton wallet. + +**Example** + +```ts +const selectedWallet = getSelectedWallet(appKit); +if (!selectedWallet) { + console.log('No wallet selected'); + return; +} + +const address = await getJettonWalletAddress(appKit, { + jettonAddress: 'EQDBE420tTQIkoWcZ9pEOTKY63WVmwyIl3hH6yWl0r_h51Tl', + ownerAddress: selectedWallet.getAddress(), +}); +console.log('Jetton Wallet Address:', address); +``` + +#### getJettons + +List jettons held by the currently selected wallet, returning `null` when no wallet is selected (use [`getJettonsByAddress`](#getjettonsbyaddress) for an arbitrary address). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options` | [`GetJettonsOptions`](#getjettonsoptions) | Optional network override and pagination. | +| `options.network` | Network | Network to read jettons from. Defaults to the selected wallet's network. | +| `options.limit` | `number` | Maximum number of jettons to return. | +| `options.offset` | `number` | Number of jettons to skip before returning results — used for pagination. | + +Returns: Promise<GetJettonsReturnType> — Jettons response for the selected wallet, or `null` when none is selected. + +**Example** + +```ts +const response = await getJettons(appKit); +if (!response) { + console.log('No wallet selected or no jettons found'); + return; +} +console.log('Jettons:', response.jettons.length); +response.jettons.forEach((j) => console.log(`- ${j.info.name}: ${j.balance}`)); +``` + +#### getJettonsByAddress + +List jettons held by an arbitrary address — useful for inspecting wallets that aren't selected in AppKit (use [`getJettons`](#getjettons) for the selected wallet). Raw balances are formatted with each jetton's declared decimals, and entries without decimals are dropped. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetJettonsByAddressOptions`](#getjettonsbyaddressoptions) | Owner address, optional network override and pagination. | +| `options.address`\* | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `options.network` | Network | Network to read the jettons from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `options.limit` | `number` | Maximum number of jettons to return. | +| `options.offset` | `number` | Number of jettons to skip before returning results — used for pagination. | + +Returns: Promise<GetJettonsByAddressReturnType> — Jettons response with formatted balances. + +**Example** + +```ts +const selectedWallet = getSelectedWallet(appKit); +if (!selectedWallet) { + console.log('No wallet selected'); + return; +} + +const response = await getJettonsByAddress(appKit, { + address: selectedWallet.getAddress(), +}); +console.log('Jettons by Address:', response.jettons.length); +response.jettons.forEach((j) => console.log(`- ${j.info.name}: ${j.balance}`)); +``` + +#### transferJetton + +Build and send a jetton transfer from the selected wallet in one step (use [`createTransferJettonTransaction`](#createtransferjettontransaction) + [`sendTransaction`](#sendtransaction) if you need to inspect the transaction first). Throws `Error('Wallet not connected')` if no wallet is currently selected. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`TransferJettonParameters`](#transferjettonparameters) | Jetton, recipient, amount, decimals and optional comment. | +| `parameters.jettonAddress`\* | UserFriendlyAddress | Jetton master contract address being transferred. | +| `parameters.recipientAddress`\* | UserFriendlyAddress | Recipient who should receive the jettons. | +| `parameters.amount`\* | `string` | Amount in jetton units as a human-readable decimal string (e.g., `"1.5"`). | +| `parameters.jettonDecimals`\* | `number` | Decimals declared by the jetton master. Used to convert `amount` into raw smallest units. | +| `parameters.comment` | `string` | Optional human-readable comment attached to the transfer. | + +Returns: Promise<TransferJettonReturnType> — Wallet response carrying the BoC of the sent transaction. + +**Example** + +```ts +const result = await transferJetton(appKit, { + jettonAddress: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs', + recipientAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + amount: '100', + jettonDecimals: 6, +}); +console.log('Transfer Result:', result); +``` + +#### watchJettons + +Subscribe to jetton-balance updates for the currently selected wallet, automatically rebinding when the user connects, switches, or disconnects (use [`watchJettonsByAddress`](#watchjettonsbyaddress) for a fixed address). Requires a streaming provider registered for the network — call throws when none is configured. Use [`hasStreamingProvider`](#hasstreamingprovider) to check first. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`WatchJettonsOptions`](#watchjettonsoptions) | Update callback and optional network override. | +| `options.onChange`\* | (update: JettonUpdate) => void | Callback fired on every jetton-balance update from the streaming provider. | +| `options.network` | Network | Network to watch on. Defaults to the selected wallet's network. | + +Returns: WatchJettonsReturnType — Unsubscribe function — call it to stop receiving updates. + +#### watchJettonsByAddress + +Subscribe to jetton-balance updates for an arbitrary owner address (use [`watchJettons`](#watchjettons) for the selected wallet). Requires a streaming provider registered for the network — call throws when none is configured. Use [`hasStreamingProvider`](#hasstreamingprovider) to check first. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`WatchJettonsByAddressOptions`](#watchjettonsbyaddressoptions) | Owner address, update callback and optional network override. | +| `options.address`\* | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `options.onChange`\* | (update: JettonUpdate) => void | Callback fired on every jetton-balance update from the streaming provider. | +| `options.network` | Network | Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +Returns: WatchJettonsByAddressReturnType — Unsubscribe function — call it to stop receiving updates. + +### NFTs + +#### createTransferNftTransaction + +Build an NFT transfer [`TransactionRequest`](#transactionrequest) for the selected wallet without sending it — useful when the UI needs to inspect or batch transactions before signing. Throws `Error('Wallet not connected')` if no wallet is currently selected. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`CreateTransferNftTransactionParameters`](#createtransfernfttransactionparameters) | NFT, recipient, optional gas amount and comment. | +| `parameters.nftAddress`\* | UserFriendlyAddress | NFT contract address to transfer. | +| `parameters.recipientAddress`\* | UserFriendlyAddress | New owner address. | +| `parameters.amount` | `string` | Amount of TON to attach to the transfer for gas. Defaults to AppKit's NFT gas-fee constant when omitted. | +| `parameters.comment` | `string` | Optional human-readable comment attached to the transfer. | + +Returns: Promise<CreateTransferNftTransactionReturnType> — Transaction request ready to pass to `sendTransaction`. + +**Example** + +```ts +const tx = await createTransferNftTransaction(appKit, { + nftAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + recipientAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + comment: 'Gift NFT', +}); + +console.log('NFT Transfer Transaction:', tx); +``` + +#### getNft + +Fetch metadata and ownership for a single NFT by its contract address. Returns `null` when the indexer has no record. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetNftOptions`](#getnftoptions) | NFT address and optional network override. | +| `options.address`\* | UserFriendlyAddress \| Address | NFT contract address — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `options.network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +Returns: Promise<GetNftReturnType> — NFT data, or `null` if the indexer has no record. + +**Example** + +```ts +const nft = await getNft(appKit, { + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', +}); + +if (nft) { + console.log('NFT Name:', nft.info?.name); + console.log('NFT Collection:', nft.collection?.name); +} +``` + +#### getNfts + +List NFTs held by the currently selected wallet, returning `null` when no wallet is selected (use [`getNftsByAddress`](#getnftsbyaddress) for an arbitrary address). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options` | [`GetNftsOptions`](#getnftsoptions) | Optional network override and pagination. | +| `options.network` | Network | Network to read NFTs from. Defaults to the selected wallet's network. | +| `options.limit` | `number` | Maximum number of NFTs to return. | +| `options.offset` | `number` | Number of NFTs to skip before returning results — used for pagination. | + +Returns: Promise<GetNftsReturnType> — NFTs response for the selected wallet, or `null` when none is selected. + +**Example** + +```ts +const response = await getNfts(appKit); + +if (response) { + console.log('Total NFTs:', response.nfts.length); + response.nfts.forEach((nft) => console.log(`- ${nft.info?.name}`)); +} +``` + +#### getNftsByAddress + +List NFTs held by an arbitrary address — useful for inspecting wallets that aren't selected in AppKit (use [`getNfts`](#getnfts) for the selected wallet). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetNftsByAddressOptions`](#getnftsbyaddressoptions) | Owner address, optional network override and pagination. | +| `options.address`\* | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `options.network` | Network | Network to read NFTs from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `options.limit` | `number` | Maximum number of NFTs to return. | +| `options.offset` | `number` | Number of NFTs to skip before returning results — used for pagination. | + +Returns: Promise<GetNftsByAddressReturnType> — NFTs response with the owner's items. + +**Example** + +```ts +const response = await getNftsByAddress(appKit, { + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', +}); + +console.log('NFTs by address:', response.nfts.length); +``` + +#### transferNft + +Build and send an NFT transfer from the selected wallet in one step (use [`createTransferNftTransaction`](#createtransfernfttransaction) + [`sendTransaction`](#sendtransaction) if you need to inspect the transaction first). Throws `Error('Wallet not connected')` if no wallet is currently selected. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`TransferNftParameters`](#transfernftparameters) | NFT, recipient, optional gas amount and comment. | +| `parameters.nftAddress`\* | UserFriendlyAddress | NFT contract address to transfer. | +| `parameters.recipientAddress`\* | UserFriendlyAddress | New owner address. | +| `parameters.amount` | `string` | Amount of TON to attach to the transfer for gas. Defaults to AppKit's NFT gas-fee constant when omitted. | +| `parameters.comment` | `string` | Optional human-readable comment attached to the transfer. | + +Returns: Promise<TransferNftReturnType> — Wallet response carrying the BoC of the sent transaction. + +**Example** + +```ts +const result = await transferNft(appKit, { + nftAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + recipientAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', +}); + +console.log('NFT Transfer Result:', result); +``` + +### Networks + +#### getBlockNumber + +Read the latest masterchain seqno (block number) for a network — useful for pagination cursors and freshness checks. Defaults to mainnet when no network is given. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options` | [`GetBlockNumberOptions`](#getblocknumberoptions) | Optional network override. | +| `options.network` | Network | Network to query. Defaults to mainnet when omitted. | + +Returns: Promise<GetBlockNumberReturnType> — Current masterchain seqno as a number. + +**Example** + +```ts +const blockNumber = await getBlockNumber(appKit); + +console.log('Current block number:', blockNumber); +``` + +#### getDefaultNetwork + +Read AppKit's currently configured default network — the one connectors enforce on new wallet connections. `undefined` means any registered network is allowed. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | + +Returns: GetDefaultNetworkReturnType — The default [`Network`](#network), or `undefined` if none is set. + +**Example** + +```ts +const defaultNetwork = getDefaultNetwork(appKit); +console.log('Default network:', defaultNetwork); +``` + +#### getNetwork + +Read the [`Network`](#network) the selected wallet is connected to, or `null` when no wallet is selected (use [`getDefaultNetwork`](#getdefaultnetwork) for AppKit's configured default). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | + +Returns: GetNetworkReturnType — Network of the selected wallet, or `null` when none is selected. + +**Example** + +```ts +const network = getNetwork(appKit); + +if (network) { + console.log('Current network:', network); +} +``` + +#### getNetworks + +List every network configured on this AppKit instance via [`AppKitConfig`](#appkitconfig)'s `networks`. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | + +Returns: GetNetworksReturnType — Array of configured [`Network`](#network)s. + +**Example** + +```ts +const networks = getNetworks(appKit); + +console.log('Configured networks:', networks); +``` + +#### hasStreamingProvider + +Check whether a streaming provider is registered for a network — required by [`watchBalance`](#watchbalance), [`watchJettons`](#watchjettons) and other live-update actions. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `network`\* | [`Network`](#network) | Network to check. | + +Returns: HasStreamingProviderReturnType — `true` when a streaming provider is registered for that network. + +**Example** + +```ts +const isSupported = hasStreamingProvider(appKit, Network.mainnet()); +console.log('Mainnet streaming support:', isSupported); +``` + +#### setDefaultNetwork + +Set or clear the default network — connectors enforce it on new wallet connections. Emits `NETWORKS_EVENTS.DEFAULT_CHANGED` so [`watchDefaultNetwork`](#watchdefaultnetwork) subscribers fire. Pass `undefined` to remove the constraint and allow any registered network. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`SetDefaultNetworkParameters`](#setdefaultnetworkparameters) | Network to enforce, or `undefined` to clear. | +| `parameters.network`\* | Network \| undefined | Network to enforce on new wallet connections. Pass `undefined` to allow any registered network. | + +Returns: SetDefaultNetworkReturnType. + +**Example** + +```ts +// Enforce testnet for all new wallet connections +setDefaultNetwork(appKit, { network: Network.testnet() }); + +// Allow any network (clear default) +setDefaultNetwork(appKit, { network: undefined }); +``` + +#### watchDefaultNetwork + +Subscribe to default-network changes — fires when [`setDefaultNetwork`](#setdefaultnetwork) is called. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`WatchDefaultNetworkParameters`](#watchdefaultnetworkparameters) | Update callback. | +| `parameters.onChange`\* | (network: Network \| undefined) => void | Callback fired whenever [`setDefaultNetwork`](#setdefaultnetwork) updates the default — receives the new value (or `undefined` when cleared). | + +Returns: WatchDefaultNetworkReturnType — Unsubscribe function — call it to stop receiving updates. + +**Example** + +```ts +const unsubscribe = watchDefaultNetwork(appKit, { + onChange: (network) => { + console.log('Default network changed:', network); + }, +}); + +// Later: unsubscribe(); +``` + +#### watchNetworks + +Subscribe to changes of the configured-networks list — fires when AppKit's network manager registers or replaces a network's API client. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`WatchNetworksParameters`](#watchnetworksparameters) | Update callback. | +| `parameters.onChange`\* | (networks: Network[]) => void | Callback fired whenever the configured-networks list changes — receives the latest snapshot. | + +Returns: WatchNetworksReturnType — Unsubscribe function — call it to stop receiving updates. + +**Example** + +```ts +const unsubscribe = watchNetworks(appKit, { + onChange: (networks) => { + console.log('Networks updated:', networks); + }, +}); + +// Later: unsubscribe(); +``` + +### Signing + +#### signBinary + +Ask the selected wallet to sign a binary blob. Throws `Error('Wallet not connected')` if no wallet is currently selected. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`SignBinaryParameters`](#signbinaryparameters) | Binary content and optional network override. | +| `parameters.bytes`\* | Base64String | Binary blob the user is asked to sign, encoded as Base64. | +| `parameters.network` | Network | Network to issue the sign request against. Defaults to AppKit's configured default network. When none is set, the wallet falls back to its current network. | + +Returns: Promise<SignBinaryReturnType> — Signature and signed payload, as returned by the wallet. + +**Example** + +```ts +// Example: sign "Hello" in base64 +const result = await signBinary(appKit, { + bytes: 'SGVsbG8=' as Base64String, +}); + +console.log('Binary Signature:', result.signature); +``` + +#### signCell + +Ask the selected wallet to sign a TON cell — typically used so the signature can later be verified on-chain. Throws `Error('Wallet not connected')` if no wallet is currently selected. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`SignCellParameters`](#signcellparameters) | Cell content, TL-B schema and optional network override. | +| `parameters.cell`\* | Base64String | TON cell content encoded as Base64 (BoC). | +| `parameters.schema`\* | `string` | TL-B-style schema describing the cell layout so the wallet can render the payload to the user. | +| `parameters.network` | Network | Network to issue the sign request against. Defaults to AppKit's configured default network. When none is set, the wallet falls back to its current network. | + +Returns: Promise<SignCellReturnType> — Signature and signed payload, as returned by the wallet. + +**Example** + +```ts +const result = await signCell(appKit, { + cell: 'te6ccgEBAQEAAgAAGA==' as Base64String, // Example BoC + schema: 'transfer#abc123 amount:uint64 = Transfer', +}); + +console.log('Cell Signature:', result.signature); +``` + +#### signText + +Ask the selected wallet to sign a plain text message. Throws `Error('Wallet not connected')` if no wallet is currently selected. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`SignTextParameters`](#signtextparameters) | Text to sign and optional network override. | +| `parameters.text`\* | `string` | UTF-8 text the user is asked to sign. | +| `parameters.network` | Network | Network to issue the sign request against. Defaults to AppKit's configured default network. When none is set, the wallet falls back to its current network. | + +Returns: Promise<SignTextReturnType> — Signature and signed payload, as returned by the wallet. + +**Example** + +```ts +const result = await signText(appKit, { + text: 'Hello, TON!', +}); + +console.log('Signature:', result.signature); +``` + +### Staking + +#### buildStakeTransaction + +Build a [`TransactionRequest`](#transactionrequest) that executes a stake or unstake previously quoted by [`getStakingQuote`](#getstakingquote) — returns it without sending so the UI can inspect or batch before signing. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`BuildStakeTransactionOptions`](#buildstaketransactionoptions) | Quote and optional provider override. | +| `options.quote`\* | StakingQuote | The staking quote based on which the transaction is built | +| `options.userAddress`\* | UserFriendlyAddress | Address of the user performing the staking | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.providerId` | `string` | Provider to stake/unstake through. Defaults to the registered default staking provider. | + +Returns: BuildStakeTransactionReturnType — Transaction request ready to pass to `sendTransaction`. + +**Example** + +```ts +const txRequest = await buildStakeTransaction(appKit, { + quote, + userAddress, +}); +console.log('Stake Transaction:', txRequest); +``` + +#### createTonstakersProvider + +Build a Tonstakers-backed [`StakingProvider`](#stakingprovider) for AppKit. Pass the result to [`AppKitConfig`](#appkitconfig)'s `providers` or [`registerProvider`](#registerprovider). + +| Parameter | Type | Description | +| --- | --- | --- | +| `config` | TonStakersProviderConfig | Optional [`TonStakersProviderConfig`](#tonstakersproviderconfig). Defaults are filled in for any field left undefined. | + +Returns: (ctx: ProviderFactoryContext) => TonStakersStakingProvider. + +#### getStakedBalance + +Read a user's staked balance from a staking provider — total staked plus, depending on the provider, any instant-unstake balance available right now. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetStakedBalanceOptions`](#getstakedbalanceoptions) | Owner address and optional network/provider override. | +| `options.userAddress`\* | UserFriendlyAddress | Owner whose staked balance should be read. | +| `options.network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `options.providerId` | `string` | Provider to query. Defaults to the registered default staking provider. | + +Returns: GetStakedBalanceReturnType — Staked-balance breakdown ([`StakingBalance`](#stakingbalance)) for the user on the resolved network/provider. + +**Example** + +```ts +const balance = await getStakedBalance(appKit, { + userAddress, +}); +console.log('Staked Balance:', balance); +``` + +#### getStakingManager + +Read AppKit's [`StakingManager`](#stakingmanager) — the runtime that owns registered staking providers and dispatches quote/stake/balance calls. Apps usually use the higher-level actions ([`getStakingQuote`](#getstakingquote), [`buildStakeTransaction`](#buildstaketransaction), [`getStakedBalance`](#getstakedbalance)) instead of touching the manager directly. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | + +Returns: GetStakingManagerReturnType — The [`StakingManager`](#stakingmanager) bound to this AppKit instance. + +#### getStakingProvider + +Get a registered staking provider by id, or the default staking provider when no id is given. Throws when no provider matches — or when no id is passed and no default has been registered. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options` | [`GetStakingProviderOptions`](#getstakingprovideroptions) | Optional provider id. | +| `options.id` | `string` | Provider ID to look up. When omitted, returns the registered default staking provider. | + +Returns: GetStakingProviderReturnType — The matching staking provider instance. + +#### getStakingProviderInfo + +Read live staking-pool info for a provider — APY, instant-unstake liquidity and (for liquid staking) the current exchange rate between stake and receive tokens. Use [`getStakingProviderMetadata`](#getstakingprovidermetadata) for static metadata (display name, stake/receive tokens, supported unstake modes). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options` | [`GetStakingProviderInfoOptions`](#getstakingproviderinfooptions) | Optional network and provider override. | +| `options.network` | Network | Network whose staking pool should be inspected. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `options.providerId` | `string` | Provider to query. Defaults to the registered default staking provider. | + +Returns: GetStakingProviderInfoReturnType — Live staking-provider info for the resolved network. + +**Example** + +```ts +const providerInfo = await getStakingProviderInfo(appKit, { + providerId: 'tonstakers', +}); +console.log('Provider Info:', providerInfo); +``` + +#### getStakingProviderMetadata + +Read static metadata for a staking provider — display name, stake/receive tokens, supported unstake modes, contract address. Use [`getStakingProviderInfo`](#getstakingproviderinfo) for live values (APY, instant-unstake liquidity, exchange rate). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options` | [`GetStakingProviderMetadataOptions`](#getstakingprovidermetadataoptions) | Optional network and provider override. | +| `options.network` | Network | Network whose provider metadata should be read. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `options.providerId` | `string` | Provider to query. Defaults to the registered default staking provider. | + +Returns: GetStakingProviderMetadataReturnType — Static [`StakingProviderMetadata`](#stakingprovidermetadata) for the resolved provider. + +**Example** + +```ts +const providerMetadata = getStakingProviderMetadata(appKit, { + providerId: 'tonstakers', +}); +console.log('Provider Metadata:', providerMetadata); +``` + +#### getStakingProviders + +List every staking provider registered on this AppKit instance — both those passed via [`AppKitConfig`](#appkitconfig)'s `providers` and those added later through [`registerProvider`](#registerprovider). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | + +Returns: GetStakingProvidersReturnType — Array of registered staking providers. + +**Example** + +```ts +const providers = getStakingProviders(appKit); +console.log('Available Staking Providers:', providers); +``` + +#### getStakingQuote + +Quote a stake or unstake — given the amount, direction and target asset, returns the rate, expected output and provider metadata needed to call [`buildStakeTransaction`](#buildstaketransaction). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetStakingQuoteOptions`](#getstakingquoteoptions) | Quote parameters and optional provider override. | +| `options.direction`\* | StakingQuoteDirection | Direction of the quote (stake or unstake) | +| `options.amount`\* | `string` | Amount of tokens to stake or unstake | +| `options.userAddress` | UserFriendlyAddress | Address of the user | +| `options.network` | Network | Network on which the staking will be executed | +| `options.unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | +| `options.isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.providerId` | `string` | Provider to quote against. Defaults to the registered default staking provider. | + +Returns: GetStakingQuoteReturnType — Quote with pricing details and provider metadata. + +**Example** + +```ts +const quote = await getStakingQuote(appKit, { + amount: '1000000000', + direction: 'stake', +}); +console.log('Staking Quote:', quote); +``` + +#### setDefaultStakingProvider + +Set the default staking provider — subsequent [`getStakingQuote`](#getstakingquote) and [`buildStakeTransaction`](#buildstaketransaction) calls without an explicit `providerId` route through it. Emits `provider:default-changed`, picked up by [`watchStakingProviders`](#watchstakingproviders). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`SetDefaultStakingProviderParameters`](#setdefaultstakingproviderparameters) | ID of the provider to make default. | +| `parameters.providerId`\* | `string` | ID of the provider to make default — must already be registered. | + +Returns: SetDefaultStakingProviderReturnType. + +#### watchStakingProviders + +Subscribe to staking provider lifecycle — fires `onChange` whenever a new provider is registered or the default staking provider switches. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`WatchStakingProvidersParameters`](#watchstakingprovidersparameters) | Update callback. | +| `parameters.onChange`\* | `() => void` | Callback fired whenever a staking provider is registered or the default staking provider changes. | + +Returns: WatchStakingProvidersReturnType — Unsubscribe function — call it to stop receiving updates. + +### Swap + +#### buildSwapTransaction + +Build a [`TransactionRequest`](#transactionrequest) that executes a swap previously quoted by [`getSwapQuote`](#getswapquote) — returns it without sending so the UI can inspect or batch before signing. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`BuildSwapTransactionOptions`](#buildswaptransactionoptions) | Quote and provider-specific options. | +| `options.quote`\* | SwapQuote | The swap quote based on which the transaction is built | +| `options.userAddress`\* | UserFriendlyAddress | Address of the user performing the swap | +| `options.destinationAddress` | UserFriendlyAddress | Address to receive the swapped tokens (defaults to userAddress) | +| `options.slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | +| `options.deadline` | `number` | Unix timestamp (in seconds) after which the swap transaction must not be executed. | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | + +Returns: BuildSwapTransactionReturnType — Transaction request ready to pass to `sendTransaction`. + +**Example** + +```ts +const transactionRequest = await buildSwapTransaction(appKit, { + quote, + userAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + slippageBps: 100, // 1% +}); +const transactionResponse = await sendTransaction(appKit, transactionRequest); +console.log('Swap Transaction:', transactionResponse); +``` + +#### createDeDustProvider + +Build a DeDust-backed [`SwapProvider`](#swapprovider) for AppKit. Pass the result to [`AppKitConfig`](#appkitconfig)'s `providers` or [`registerProvider`](#registerprovider). + +| Parameter | Type | Description | +| --- | --- | --- | +| `config` | DeDustSwapProviderConfig | Optional [`DeDustSwapProviderConfig`](#dedustswapproviderconfig). Defaults are filled in for any field left undefined. | + +Returns: (ctx: ProviderFactoryContext) => DeDustSwapProvider. + +#### createOmnistonProvider + +Build an Omniston-backed [`SwapProvider`](#swapprovider) for AppKit. Pass the result to [`AppKitConfig`](#appkitconfig)'s `providers` or [`registerProvider`](#registerprovider). + +| Parameter | Type | Description | +| --- | --- | --- | +| `config` | OmnistonSwapProviderConfig | Optional [`OmnistonSwapProviderConfig`](#omnistonswapproviderconfig). Defaults are filled in for any field left undefined. | + +Returns: (ctx: ProviderFactoryContext) => OmnistonSwapProvider. + +#### getSwapManager + +Read AppKit's [`SwapManager`](#swapmanager) — the runtime that owns registered swap providers and dispatches quote/build calls. Apps usually use the higher-level actions ([`getSwapQuote`](#getswapquote), [`buildSwapTransaction`](#buildswaptransaction)) instead of touching the manager directly. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | + +Returns: GetSwapManagerReturnType — The [`SwapManager`](#swapmanager) bound to this AppKit instance. + +**Example** + +```ts +const swapManager = getSwapManager(appKit); +``` + +#### getSwapProvider + +Get a registered swap provider by id, or the default swap provider when no id is given. Throws when no provider matches — or when no id is passed and no default has been registered. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options` | [`GetSwapProviderOptions`](#getswapprovideroptions) | Optional provider id. | +| `options.id` | `string` | Provider ID to look up. When omitted, returns the registered default swap provider. | + +Returns: GetSwapProviderReturnType — The matching swap provider instance. + +**Example** + +```ts +const swapProvider = getSwapProvider(appKit, { id: 'stonfi' }); +``` + +#### getSwapProviders + +List every swap provider registered on this AppKit instance — both those passed via [`AppKitConfig`](#appkitconfig)'s `providers` and those added later through [`registerProvider`](#registerprovider). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | + +Returns: GetSwapProvidersReturnType — Array of registered swap providers. + +**Example** + +```ts +const swapProviders = getSwapProviders(appKit); +console.log( + 'Registered providers:', + swapProviders.map((p) => p.providerId), +); +``` + +#### getSwapQuote + +Quote a swap — given source/target tokens and an amount, returns the rate, expected output and provider metadata needed to call [`buildSwapTransaction`](#buildswaptransaction). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`GetSwapQuoteOptions`](#getswapquoteoptions) | Source and target tokens, amount, optional network and provider override. | +| `options.amount`\* | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | +| `options.from`\* | SwapToken | Token to swap from | +| `options.to`\* | SwapToken | Token to swap to | +| `options.network`\* | Network | Network on which the swap will be executed | +| `options.slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | +| `options.maxOutgoingMessages` | `number` | Maximum number of outgoing messages | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | +| `options.providerId` | `string` | Provider to quote against. Defaults to the registered default swap provider. | + +Returns: GetSwapQuoteReturnType — Quote with pricing details and the provider metadata required to build a transaction. + +**Example** + +```ts +const quote = await getSwapQuote(appKit, { + from: { + address: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs', + decimals: 6, + }, + to: { address: 'ton', decimals: 9 }, + amount: '1000000000', // nanotons as string + network: Network.mainnet(), +}); +console.log('Swap Quote:', quote); +``` + +#### setDefaultSwapProvider + +Set the default swap provider — subsequent [`getSwapQuote`](#getswapquote) and [`buildSwapTransaction`](#buildswaptransaction) calls without an explicit `providerId` route through it. Emits `provider:default-changed`, picked up by [`watchSwapProviders`](#watchswapproviders). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`SetDefaultSwapProviderParameters`](#setdefaultswapproviderparameters) | ID of the provider to make default. | +| `parameters.providerId`\* | `string` | ID of the provider to make default — must already be registered. | + +Returns: SetDefaultSwapProviderReturnType. + +**Example** + +```ts +setDefaultSwapProvider(appKit, { providerId: 'stonfi' }); +``` + +#### watchSwapProviders + +Subscribe to swap provider lifecycle — fires `onChange` whenever a new provider is registered or the default swap provider switches. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`WatchSwapProvidersParameters`](#watchswapprovidersparameters) | Update callback. | +| `parameters.onChange`\* | `() => void` | Callback fired whenever a swap provider is registered or the default swap provider changes. | + +Returns: WatchSwapProvidersReturnType — Unsubscribe function — call it to stop receiving updates. + +**Example** + +```ts +const unsubscribe = watchSwapProviders(appKit, { + onChange: () => console.log('Swap providers updated'), +}); +unsubscribe(); +``` + +### Transactions + +#### createTransferTonTransaction + +Build a TON transfer [`TransactionRequest`](#transactionrequest) for the selected wallet without sending it — useful when the UI needs to inspect or batch transactions before signing. Throws `Error('Wallet not connected')` if no wallet is currently selected. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`CreateTransferTonTransactionParameters`](#createtransfertontransactionparameters) | Recipient, amount and optional payload/comment/stateInit. | +| `parameters.recipientAddress`\* | UserFriendlyAddress | Recipient address. | +| `parameters.amount`\* | `string` | Amount in TON as a human-readable decimal string (e.g., `"1.5"`). Converted to nano-TON internally. | +| `parameters.comment` | `string` | Human-readable text comment. Converted to a Base64 payload when no `payload` is supplied. | +| `parameters.payload` | Base64String | Raw Base64 message payload — wins over `comment` when both are set. | +| `parameters.stateInit` | Base64String | Initial state for deploying a new contract, encoded as Base64. | + +Returns: CreateTransferTonTransactionReturnType — Transaction request ready to pass to `sendTransaction`. + +**Example** + +```ts +const tx = createTransferTonTransaction(appKit, { + recipientAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + amount: '0.1', // 0.1 TON (human-readable format) + comment: 'Draft transaction', +}); + +console.log('Transaction Request:', tx); +``` + +#### getTransactionStatus + +Read the status of a sent transaction by its BoC or normalized hash. In TON a single external message triggers a tree of internal messages — the transaction is `'completed'` only when the entire trace finishes. Until then it stays `'pending'`. Throws when neither `boc` nor `normalizedHash` is provided. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`GetTransactionStatusParameters`](#gettransactionstatusparameters) | Exactly one of `boc` or `normalizedHash`, plus an optional network override. | + +Returns: Promise<GetTransactionStatusReturnType> — Status response with current state, completed/total message counts and trace details. + +#### sendTransaction + +Hand a pre-built [`TransactionRequest`](#transactionrequest) to the selected wallet for signing and broadcast — usually the second step after [`createTransferTonTransaction`](#createtransfertontransaction), [`buildSwapTransaction`](#buildswaptransaction) or [`buildStakeTransaction`](#buildstaketransaction). Throws `Error('Wallet not connected')` if no wallet is currently selected. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`SendTransactionParameters`](#sendtransactionparameters) | Transaction request to broadcast. | + +Returns: Promise<SendTransactionReturnType> — Wallet response carrying the BoC of the sent transaction. + +**Example** + +```ts +const result = await sendTransaction(appKit, { + messages: [ + { + address: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + amount: '100000000', // 0.1 TON in nanotons (raw format) + }, + ], +}); + +console.log('Transaction Result:', result); +``` + +#### transferTon + +Build and send a TON transfer from the selected wallet in one step (use [`createTransferTonTransaction`](#createtransfertontransaction) + [`sendTransaction`](#sendtransaction) if you need to inspect the transaction first). Throws `Error('Wallet not connected')` if no wallet is currently selected. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`TransferTonParameters`](#transfertonparameters) | Recipient, amount and optional payload/comment/stateInit. | +| `parameters.recipientAddress`\* | UserFriendlyAddress | Recipient address. | +| `parameters.amount`\* | `string` | Amount in TON as a human-readable decimal string (e.g., `"1.5"`). Converted to nano-TON internally. | +| `parameters.comment` | `string` | Human-readable text comment. Converted to a Base64 payload when no `payload` is supplied. | +| `parameters.payload` | Base64String | Raw Base64 message payload — wins over `comment` when both are set. | +| `parameters.stateInit` | Base64String | Initial state for deploying a new contract, encoded as Base64. | + +Returns: Promise<TransferTonReturnType> — Wallet response carrying the BoC of the sent transaction. + +**Example** + +```ts +const result = await transferTon(appKit, { + recipientAddress: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c', + amount: '0.1', // 0.1 TON (human-readable format) + comment: 'Hello from AppKit!', +}); + +console.log('Transfer Result:', result); +``` + +#### watchTransactions + +Subscribe to incoming-transaction events for the currently selected wallet, automatically rebinding when the user connects, switches, or disconnects (use [`watchTransactionsByAddress`](#watchtransactionsbyaddress) for a fixed address). Requires a streaming provider registered for the network — call throws when none is configured. Use [`hasStreamingProvider`](#hasstreamingprovider) to check first. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`WatchTransactionsOptions`](#watchtransactionsoptions) | Update callback and optional network override. | +| `options.onChange`\* | (update: TransactionsUpdate) => void | Callback fired on every transactions update from the streaming provider. | +| `options.network` | Network | Network to watch on. Defaults to the selected wallet's network. | + +Returns: WatchTransactionsReturnType — Unsubscribe function — call it to stop receiving updates. + +#### watchTransactionsByAddress + +Subscribe to incoming-transaction events for an arbitrary address (use [`watchTransactions`](#watchtransactions) for the selected wallet). Requires a streaming provider registered for the network — call throws when none is configured. Use [`hasStreamingProvider`](#hasstreamingprovider) to check first. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `options`\* | [`WatchTransactionsByAddressOptions`](#watchtransactionsbyaddressoptions) | Address, update callback and optional network override. | +| `options.address`\* | UserFriendlyAddress \| Address | Address to watch — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `options.onChange`\* | (update: TransactionsUpdate) => void | Callback fired on every transactions update from the streaming provider. | +| `options.network` | Network | Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +Returns: WatchTransactionsByAddressReturnType — Unsubscribe function — call it to stop receiving updates. + +### Wallets + +#### getConnectedWallets + +List every wallet currently connected through any registered [`Connector`](#connector). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | + +Returns: GetConnectedWalletsReturnType — Read-only array of [`WalletInterface`](#walletinterface)s. + +**Example** + +```ts +const wallets = getConnectedWallets(appKit); + +console.log('Connected wallets:', wallets); +``` + +#### getSelectedWallet + +Read the wallet AppKit treats as "active" — most actions ([`getBalance`](#getbalance), [`signText`](#signtext), [`transferTon`](#transferton)) target this wallet implicitly. Returns `null` when no wallet is connected or selected. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | + +Returns: GetSelectedWalletReturnType — Selected [`WalletInterface`](#walletinterface), or `null` when none is selected. + +**Example** + +```ts +const wallet = getSelectedWallet(appKit); + +if (wallet) { + console.log('Selected wallet:', wallet.getWalletId()); + console.log('Address:', wallet.getAddress()); +} +``` + +#### setSelectedWalletId + +Switch which connected wallet AppKit treats as selected — emits `WALLETS_EVENTS.SELECTION_CHANGED` so [`watchSelectedWallet`](#watchselectedwallet) subscribers fire. Pass `null` to clear the selection. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`SetSelectedWalletIdParameters`](#setselectedwalletidparameters) | Wallet ID to select, or `null` to clear. | +| `parameters.walletId`\* | `string \| null` | Wallet ID (as returned by [`WalletInterface`](#walletinterface)'s `getWalletId()`) to select. Pass `null` to clear the selection. | + +Returns: SetSelectedWalletIdReturnType. + +**Example** + +```ts +setSelectedWalletId(appKit, { + walletId: 'my-wallet-id', +}); +``` + +#### watchConnectedWallets + +Subscribe to the list of connected wallets — fires whenever a wallet connects or disconnects through any registered [`Connector`](#connector). + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`WatchConnectedWalletsParameters`](#watchconnectedwalletsparameters) | Update callback. | +| `parameters.onChange`\* | (wallets: WalletInterface[]) => void | Callback fired whenever the list of connected wallets changes — receives the latest snapshot. | + +Returns: WatchConnectedWalletsReturnType — Unsubscribe function — call it to stop receiving updates. + +**Example** + +```ts +const unsubscribe = watchConnectedWallets(appKit, { + onChange: (wallets) => { + console.log('Connected wallets updated:', wallets.length); + }, +}); + +// Later: unsubscribe(); +``` + +#### watchSelectedWallet + +Subscribe to selected-wallet changes — fires when [`setSelectedWalletId`](#setselectedwalletid) runs, when the wallet manager auto-selects the first wallet because no prior selection survived a connector update, or when it clears the selection because no connected wallets remain. + +| Parameter | Type | Description | +| --- | --- | --- | +| `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | +| `parameters`\* | [`WatchSelectedWalletParameters`](#watchselectedwalletparameters) | Update callback. | +| `parameters.onChange`\* | (wallet: WalletInterface \| null) => void | Callback fired whenever the selected wallet changes — receives the new wallet, or `null` when the selection was cleared. | + +Returns: WatchSelectedWalletReturnType — Unsubscribe function — call it to stop receiving updates. + +**Example** + +```ts +const unsubscribe = watchSelectedWallet(appKit, { + onChange: (wallet) => { + if (wallet) { + console.log('Selected wallet changed:', wallet.getWalletId()); + } else { + console.log('Wallet deselected'); + } + }, +}); + +// Later: unsubscribe(); +``` + +## Class + +### Client + +#### ApiClientTonApi + +[`ApiClient`](#apiclient) implementation backed by the TonAPI indexer. + +Constructor: `new ApiClientTonApi(config)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `config` | [`BaseApiClientConfig`](#baseapiclientconfig) | TonAPI client config — endpoint URL and API key. Defaults to TonAPI mainnet/testnet URLs based on `config.network`. | +| `config.endpoint` | `string` | Base URL of the indexer endpoint. Defaults to the provider's mainnet/testnet URL based on `network`. | +| `config.apiKey` | `string` | API key forwarded to the indexer for higher rate limits. | +| `config.timeout` | `number` | Per-request timeout in milliseconds. Defaults to a provider-specific value. | +| `config.fetchApi` | `typeof fetch` | Custom `fetch` implementation. Defaults to the global `fetch`. | +| `config.network` | Network | [`Network`](#network) the client should target. Determines the default `endpoint` when one isn't supplied. | +| `config.disableNetworkSend` | `boolean` | When `true`, swallow `sendBoc` calls instead of broadcasting them — useful for local development and tests. | + +#### ApiClientToncenter + +[`ApiClient`](#apiclient) implementation backed by the Toncenter API. + +Constructor: `new ApiClientToncenter(config)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `config` | [`ApiClientToncenterConfig`](#apiclienttoncenterconfig) | Toncenter client config — endpoint URL, API key and optional DNS resolver override. Defaults to mainnet/testnet Toncenter URLs based on `config.network`. | +| `config.dnsResolver` | `string` | Override the contract address used to resolve TON DNS records. Defaults to the network's standard root resolver. | +| `config.endpoint` | `string` | Base URL of the indexer endpoint. Defaults to the provider's mainnet/testnet URL based on `network`. | +| `config.apiKey` | `string` | API key forwarded to the indexer for higher rate limits. | +| `config.timeout` | `number` | Per-request timeout in milliseconds. Defaults to a provider-specific value. | +| `config.fetchApi` | `typeof fetch` | Custom `fetch` implementation. Defaults to the global `fetch`. | +| `config.network` | Network | [`Network`](#network) the client should target. Determines the default `endpoint` when one isn't supplied. | +| `config.disableNetworkSend` | `boolean` | When `true`, swallow `sendBoc` calls instead of broadcasting them — useful for local development and tests. | + +### Core + +#### AppKit + +Runtime that wires connectors, networks, providers and the event emitter for a TON dApp. Construct once at startup and reuse for the app's lifetime. + +Constructor: `new AppKit(config)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `config`\* | [`AppKitConfig`](#appkitconfig) | Networks, connectors, providers and runtime flags. | +| `config.networks` | NetworkAdapters | Map of chain ID to [`NetworkConfig`](#networkconfig) (which holds the api-client setup). If omitted, AppKit defaults to mainnet only. | +| `config.connectors` | ConnectorInput[] | Wallet connectors registered at startup. | +| `config.defaultNetwork` | Network | Default network. | +| `config.providers` | ProviderInput[] | Providers registered at startup. | + +**Example** + +```ts +// Initialize AppKit +const appKit = new AppKit({ + networks: { + [Network.mainnet().chainId]: { + apiClient: { + url: 'https://toncenter.com', + key: 'your-key', + }, + }, + // Optional: add testnet + // [Network.testnet().chainId]: { + // apiClient: { + // url: 'https://testnet.toncenter.com', + // key: 'your-key', + // }, + // }, + }, + connectors: [ + createTonConnectConnector({ + tonConnectOptions: { + manifestUrl: 'https://tonconnect-sdk-demo-dapp.vercel.app/tonconnect-manifest.json', + }, + }), + ], +}); +``` + +#### EventEmitter + +Strongly-typed event emitter built on a string event name → payload type map. Type of `appKit.emitter` and the base for any custom emitters apps create. See [`AppKitEvents`](#appkitevents) for the full list of events AppKit emits. `appKit.emitter.on(name, handler)` returns an unsubscribe function. + +Constructor: `new EventEmitter()` + +### Crypto Onramp + +#### CryptoOnrampError + +Error thrown by [`CryptoOnrampManager`](#cryptoonrampmanager) and crypto-onramp providers — extends [`DefiError`](#defierror) with `name: 'CryptoOnrampError'` and a typed [`CryptoOnrampErrorCode`](#cryptoonramperrorcode) on `code`. + +Constructor: `new CryptoOnrampError(message, code, details)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `message`\* | `string` | Human-readable description, forwarded to `Error`. | +| `code`\* | [`CryptoOnrampErrorCode`](#cryptoonramperrorcode) | Stable error code for branching logic. | +| `details` | `unknown` | Optional provider-specific context for diagnostics. | + +#### CryptoOnrampManager + +Runtime that owns registered [`CryptoOnrampProvider`](#cryptoonrampprovider)s and dispatches quote/deposit/status calls. Usually accessed through the higher-level actions ([`getCryptoOnrampQuote`](#getcryptoonrampquote), [`createCryptoOnrampDeposit`](#createcryptoonrampdeposit), [`getCryptoOnrampStatus`](#getcryptoonrampstatus)). + +Constructor: `new CryptoOnrampManager()` + +#### CryptoOnrampProvider + +Abstract base class implemented by crypto-onramp providers (Layerswap, swaps.xyz, custom integrations). Apps don't use it directly — they consume providers through [`CryptoOnrampManager`](#cryptoonrampmanager) and the `getCryptoOnramp*` / [`createCryptoOnrampDeposit`](#createcryptoonrampdeposit) actions. + +Constructor: `new CryptoOnrampProvider()` + +#### LayerswapCryptoOnrampProvider + +[`CryptoOnrampProvider`](#cryptoonrampprovider) implementation backed by Layerswap. Prefer the [`createLayerswapProvider`](#createlayerswapprovider) factory over instantiating this class directly — the factory returns a `ProviderInput` ready to pass to [`AppKitConfig`](#appkitconfig)'s `providers` or [`registerProvider`](#registerprovider). + +Constructor: `new LayerswapCryptoOnrampProvider(config)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `config` | LayerswapProviderConfig | Optional [`LayerswapProviderConfig`](#layerswapproviderconfig). Defaults are filled in for any field left undefined. | +| `config.apiKey` | `string` | Optional API key. Forwarded as `X-LS-APIKEY` when provided. | +| `config.apiUrl` | `string` | Override the base API URL. Defaults to https://api.layerswap.io/api/v2 | + +#### SwapsXyzCryptoOnrampProvider + +[`CryptoOnrampProvider`](#cryptoonrampprovider) implementation backed by swaps.xyz. Prefer the [`createSwapsXyzProvider`](#createswapsxyzprovider) factory over instantiating this class directly — the factory returns a `ProviderInput` ready to pass to [`AppKitConfig`](#appkitconfig)'s `providers` or [`registerProvider`](#registerprovider). + +Constructor: `new SwapsXyzCryptoOnrampProvider(config)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `config`\* | [`SwapsXyzProviderConfig`](#swapsxyzproviderconfig) | Configuration carrying the required `apiKey` plus optional URL/sender overrides. | +| `config.apiKey`\* | `string` | API key issued by swaps.xyz (passed as `x-api-key`) | +| `config.apiUrl` | `string` | Override the base API URL. Defaults to https://api-v2.swaps.xyz/api | +| `config.defaultSender` | `string` | EVM address used as `sender` on getAction requests. Required by the API even for deposit flows where the actual payer is unknown. Defaults to a null address when omitted. | + +### DeFi + +#### DefiError + +Base error thrown across all DeFi domains (swap, staking, onramp, crypto-onramp). Subclassed by [`SwapError`](#swaperror), [`StakingError`](#stakingerror), [`CryptoOnrampError`](#cryptoonramperror) and the internal onramp error — catch the base when you don't care which domain produced the failure. + +Constructor: `new DefiError(message, code, details)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `message`\* | `string` | Human-readable description, forwarded to `Error`. | +| `code`\* | [`DefiErrorCode`](#defierrorcode) | Stable error code for branching logic. | +| `details` | `unknown` | Optional provider-specific context for diagnostics. | + +### Networks + +#### AppKitNetworkManager + +Network manager that extends walletkit's [`KitNetworkManager`](#kitnetworkmanager) with a default-network setter and AppKit event emission. Usually accessed through the higher-level actions ([`getDefaultNetwork`](#getdefaultnetwork), [`setDefaultNetwork`](#setdefaultnetwork), [`watchDefaultNetwork`](#watchdefaultnetwork), [`getNetworks`](#getnetworks), [`watchNetworks`](#watchnetworks)). + +Constructor: `new AppKitNetworkManager(options, emitter)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `options`\* | [`TonWalletKitOptions`](#tonwalletkitoptions) | Forwarded to the [`KitNetworkManager`](#kitnetworkmanager) base — chiefly the `networks` map keyed by chain ID. | +| `emitter`\* | [`AppKitEmitter`](#appkitemitter) | Emitter the manager publishes `networks:default-changed` / `networks:updated` events through. | + +#### KitNetworkManager + +Walletkit-side network manager that [`AppKitNetworkManager`](#appkitnetworkmanager) extends, adding default-network state and AppKit event emission. Apps usually interact with the [`AppKitNetworkManager`](#appkitnetworkmanager) subclass. + +Constructor: `new KitNetworkManager(options)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `options`\* | [`TonWalletKitOptions`](#tonwalletkitoptions) | Configuration carrying the `networks` map keyed by chain ID. At least one network must be configured. | + +### Staking + +#### StakingError + +Error thrown by [`StakingManager`](#stakingmanager) and staking providers — extends [`DefiError`](#defierror) with `name: 'StakingError'` and a typed [`StakingErrorCode`](#stakingerrorcode) on `code`. + +Constructor: `new StakingError(message, code, details)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `message`\* | `string` | Human-readable description, forwarded to `Error`. | +| `code`\* | [`StakingErrorCode`](#stakingerrorcode) | Stable error code for branching logic. | +| `details` | `unknown` | Optional provider-specific context for diagnostics. | + +#### StakingManager + +Runtime that owns registered [`StakingProvider`](#stakingprovider)s and dispatches quote/stake/balance calls. Usually accessed through the higher-level actions ([`getStakingQuote`](#getstakingquote), [`buildStakeTransaction`](#buildstaketransaction), [`getStakedBalance`](#getstakedbalance)). + +Constructor: `new StakingManager(createFactoryContext)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `createFactoryContext`\* | () => ProviderFactoryContext | Lazy provider of the [`ProviderFactoryContext`](#providerfactorycontext) the manager passes into provider factories at registration time. | + +#### StakingProvider + +Abstract base class implemented by staking providers (Tonstakers, custom integrations, …). Apps don't use it directly — they consume providers through [`StakingManager`](#stakingmanager) and the `getStaking*` / `buildStakeTransaction` actions. + +Constructor: `new StakingProvider(providerId)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `providerId`\* | `string` | Stable id the provider registers with — must be unique within [`StakingManager`](#stakingmanager). | + +#### TonStakersStakingProvider + +[`StakingProvider`](#stakingprovider) implementation backed by Tonstakers. The constructor is private — always go through the [`createTonstakersProvider`](#createtonstakersprovider) factory and pass the result to [`AppKitConfig`](#appkitconfig)'s `providers` or [`registerProvider`](#registerprovider). + +Constructor: `new TonStakersStakingProvider()` + +### Swap + +#### DeDustSwapProvider + +[`SwapProvider`](#swapprovider) implementation backed by DeDust. Prefer the [`createDeDustProvider`](#creatededustprovider) factory over instantiating this class directly — the factory returns a `ProviderInput` ready to pass to [`AppKitConfig`](#appkitconfig)'s `providers` or [`registerProvider`](#registerprovider). + +Constructor: `new DeDustSwapProvider(config)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `config` | DeDustSwapProviderConfig | Optional [`DeDustSwapProviderConfig`](#dedustswapproviderconfig). Defaults are filled in for any field left undefined. | +| `config.providerId` | `string` | Custom provider ID (defaults to 'dedust') | +| `config.defaultSlippageBps` | `number` | Default slippage tolerance in basis points (1 bp = 0.01%) | +| `config.apiUrl` | `string` | API base URL | +| `config.onlyVerifiedPools` | `boolean` | Only use verified pools | +| `config.maxSplits` | `number` | Maximum number of route splits | +| `config.maxLength` | `number` | Maximum route length (hops) | +| `config.minPoolUsdTvl` | `string` | Minimum pool TVL in USD | +| `config.metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider | +| `config.referralAddress` | `string` | The address of the referrer | +| `config.referralFeeBps` | `number` | Referral fee in basis points (max 100 = 1%) | + +**Example** + +```ts +kit.registerProvider( + createDeDustProvider({ + defaultSlippageBps: 100, // 1% + referralAddress: 'EQ...', + referralFeeBps: 50, // 0.5% + }), +); +``` + +#### OmnistonSwapProvider + +[`SwapProvider`](#swapprovider) implementation backed by Omniston. Prefer the [`createOmnistonProvider`](#createomnistonprovider) factory over instantiating this class directly — the factory returns a `ProviderInput` ready to pass to [`AppKitConfig`](#appkitconfig)'s `providers` or [`registerProvider`](#registerprovider). + +Constructor: `new OmnistonSwapProvider(config)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `config` | OmnistonSwapProviderConfig | Optional [`OmnistonSwapProviderConfig`](#omnistonswapproviderconfig). Defaults are filled in for any field left undefined. | +| `config.apiUrl` | `string` | Optional URL for the Omniston API | +| `config.defaultSlippageBps` | `number` | Default slippage tolerance in basis points (1 bp = 0.01%) | +| `config.quoteTimeoutMs` | `number` | Timeout for quote requests in milliseconds | +| `config.providerId` | `string` | Identifier for the provider | +| `config.metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider | +| `config.referrerAddress` | `string` | The address of the referrer | +| `config.referrerFeeBps` | `number` | Referrer fee in basis points (1 bp = 0.01%) | +| `config.flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed | + +**Example** + +```ts +kit.registerProvider( + createOmnistonProvider({ + defaultSlippageBps: 100, // 1% + quoteTimeoutMs: 10000, + }), +); +``` + +#### SwapError + +Error thrown by [`SwapManager`](#swapmanager) and swap providers — extends [`DefiError`](#defierror) with `name: 'SwapError'` and a typed [`SwapErrorCode`](#swaperrorcode) on `code`. + +Constructor: `new SwapError(message, code, details)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `message`\* | `string` | Human-readable description, forwarded to `Error`. | +| `code`\* | [`SwapErrorCode`](#swaperrorcode) | Stable error code for branching logic. | +| `details` | `unknown` | Optional provider-specific context for diagnostics. | + +#### SwapManager + +Runtime that owns registered [`SwapProvider`](#swapprovider)s and dispatches quote/swap calls. Usually accessed through the higher-level actions ([`getSwapQuote`](#getswapquote), [`buildSwapTransaction`](#buildswaptransaction)). + +Constructor: `new SwapManager(createFactoryContext)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `createFactoryContext`\* | () => ProviderFactoryContext | Lazy provider of the [`ProviderFactoryContext`](#providerfactorycontext) the manager passes into provider factories at registration time. | + +#### SwapProvider + +Abstract base class implemented by swap providers (DeDust, Omniston, custom integrations). Apps don't use it directly — they consume providers through [`SwapManager`](#swapmanager) and the `getSwap*` / `buildSwapTransaction` actions. + +Constructor: `new SwapProvider()` + +### Wallets + +#### TonConnectWalletAdapter + +[`WalletInterface`](#walletinterface) implementation backed by a TonConnect wallet. Prefer the [`createTonConnectConnector`](#createtonconnectconnector) factory over instantiating this class directly — the connector builds the adapter for every wallet it tracks and apps interact with it through standard AppKit actions ([`sendTransaction`](#sendtransaction), [`signText`](#signtext)/[`signBinary`](#signbinary)/[`signCell`](#signcell)). On-chain reads (balance, jettons, NFTs) live on separate actions ([`getBalance`](#getbalance), [`getJettons`](#getjettons), [`getNfts`](#getnfts)) and don't go through this adapter. + +Constructor: `new TonConnectWalletAdapter(config)` + +| Parameter | Type | Description | +| --- | --- | --- | +| `config`\* | [`TonConnectWalletAdapterConfig`](#tonconnectwalletadapterconfig) | TonConnect wallet + UI instance and the id of the connector that produced them. | +| `config.connectorId`\* | `string` | ID of the connector that produced this wallet — surfaced as `WalletInterface.connectorId`. | +| `config.tonConnectWallet`\* | `TonConnectWallet` | Underlying TonConnect wallet object. | +| `config.tonConnectUI`\* | `TonConnectUI` | TonConnect UI instance used to drive `sendTransaction` and `signData` calls. | + +## Type + +### Balances + +#### BalanceUpdate + +Update payload delivered to [`watchBalance`](#watchbalance) / [`watchBalanceByAddress`](#watchbalancebyaddress) subscribers when the watched address's TON balance changes. + +| Field | Type | Description | +| --- | --- | --- | +| `type`\* | `'balance'` | The update type field | +| `address`\* | UserFriendlyAddress | The account address | +| `rawBalance`\* | TokenAmount | The account balance in nano units | +| `balance`\* | `string` | The formatted balance | +| `status`\* | StreamingUpdateStatus | The finality of the update | + +#### GetBalanceByAddressOptions + +Options for [`getBalanceByAddress`](#getbalancebyaddress). + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | UserFriendlyAddress \| Address | Wallet address — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `network` | Network | Network to read the balance from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +#### GetBalanceByAddressReturnType + +Return type of [`getBalanceByAddress`](#getbalancebyaddress). + +```ts +type GetBalanceByAddressReturnType = TokenAmount; +``` + +#### GetBalanceOptions + +Options for [`getBalance`](#getbalance). + +| Field | Type | Description | +| --- | --- | --- | +| `network` | Network | Network to read the balance from. Defaults to the selected wallet's network. | + +#### GetBalanceReturnType + +Return type of [`getBalance`](#getbalance). + +```ts +type GetBalanceReturnType = TokenAmount | null; +``` + +#### StreamingUpdateStatus + +Finality stage carried by every streaming update — `'pending'` (in mempool), `'confirmed'` (included in a block), `'finalized'` (irreversible), or `'invalidated'` (rolled back). + +```ts +type StreamingUpdateStatus = 'pending' | 'confirmed' | 'finalized' | 'invalidated'; +``` + +#### WatchBalanceByAddressOptions + +Options for [`watchBalanceByAddress`](#watchbalancebyaddress). + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | UserFriendlyAddress \| Address | Wallet address — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `network` | Network | Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `onChange`\* | (update: BalanceUpdate) => void | Callback fired on every balance update from the streaming provider. | + +#### WatchBalanceByAddressReturnType + +Return type of [`watchBalanceByAddress`](#watchbalancebyaddress) — call to stop receiving updates. + +```ts +type WatchBalanceByAddressReturnType = () => void; +``` + +#### WatchBalanceOptions + +Options for [`watchBalance`](#watchbalance). + +| Field | Type | Description | +| --- | --- | --- | +| `network` | Network | Network to watch on. Defaults to the selected wallet's network. | +| `onChange`\* | (update: BalanceUpdate) => void | Callback fired on every balance update from the streaming provider. | + +#### WatchBalanceReturnType + +Return type of [`watchBalance`](#watchbalance) — call to stop receiving updates. + +```ts +type WatchBalanceReturnType = () => void; +``` + +### Client + +#### AddressBook + +Map of raw addresses to their resolved metadata, returned alongside indexed lists (e.g. [`JettonsResponse`](#jettonsresponse), [`NFTsResponse`](#nftsresponse)) so consumers can render labels without extra lookups. + +```ts +type AddressBook = { + [key: UserFriendlyAddress]: AddressBookEntry; +}; +``` + +#### AddressBookEntry + +Single entry inside an [`AddressBook`](#addressbook) — pairs the user-friendly address with optional domain name and the list of contract interfaces it implements. + +| Field | Type | Description | +| --- | --- | --- | +| `address` | UserFriendlyAddress | The human-readable representation of the blockchain address | +| `domain` | `string` | The domain name associated with the address if available | +| `interfaces`\* | `string[]` | List of supported interfaces by the address | + +#### ApiClient + +Indexer/RPC client interface used by AppKit to read on-chain state — balance, jettons, NFTs, etc. Each [`Network`](#network) resolves to its own `ApiClient` via [`AppKitNetworkManager`](#appkitnetworkmanager). Apps usually pull one through [`getApiClient`](#getapiclient) rather than constructing it directly. + +| Field | Type | Description | +| --- | --- | --- | +| `nftItemsByAddress`\* | (request: NFTsRequest) => Promise<NFTsResponse> | Look up specific NFT items by address. | +| `nftItemsByOwner`\* | (request: UserNFTsRequest) => Promise<NFTsResponse> | List NFT items held by an owner. Supports pagination. | +| `fetchEmulation`\* | (messageBoc: Base64String, ignoreSignature?: boolean) => Promise<ToncenterEmulationResult> | Run an emulation pass on a Base64-encoded BoC. Returns the predicted account-state changes and emitted events without sending the message. | +| `sendBoc`\* | (boc: Base64String) => Promise<string> | Broadcast a signed BoC to the network and return the message hash. | +| `runGetMethod`\* | (address: UserFriendlyAddress, method: string, stack?: RawStackItem[], seqno?: number) => Promise<GetMethodResult> | Run an on-chain `get` method against a contract and read its TVM stack output. | +| `getAccountState`\* | (address: UserFriendlyAddress, seqno?: number) => Promise<FullAccountState> | Read the full on-chain account state (code, data, status, balance) for an address. | +| `getBalance`\* | (address: UserFriendlyAddress, seqno?: number) => Promise<TokenAmount> | Read the TON balance of an address in raw nanotons. | +| `getAccountTransactions`\* | `(request: TransactionsByAddressRequest) => Promise` | List transactions for an address. Ordered newest-first, paginated via `LimitRequest`. | +| `getTransactionsByHash`\* | `(request: GetTransactionByHashRequest) => Promise` | Fetch a transaction by its message or body hash. | +| `getPendingTransactions`\* | `(request: GetPendingTransactionsRequest) => Promise` | List pending (unconfirmed) transactions by accounts or trace ids. Useful for "in-flight" UIs. | +| `getTrace`\* | `(request: GetTraceRequest) => Promise` | Fetch a confirmed trace (the tree of internal messages spawned by an external one). | +| `getPendingTrace`\* | `(request: GetPendingTraceRequest) => Promise` | Fetch a pending trace by external-message hash, while it's still in flight. | +| `resolveDnsWallet`\* | `(domain: string) => Promise` | Resolve a TON DNS domain to the wallet address it points at. `null` when unset. | +| `backResolveDnsWallet`\* | (address: UserFriendlyAddress) => Promise<string \| null> | Reverse-resolve a wallet address to a TON DNS domain that points at it. `null` when none. | +| `jettonsByAddress`\* | `(request: GetJettonsByAddressRequest) => Promise` | Look up jetton masters by address — returns indexer metadata for the requested jettons. | +| `jettonsByOwnerAddress`\* | (request: GetJettonsByOwnerRequest) => Promise<JettonsResponse> | List jetton holdings owned by an address — returns balances + jetton-master metadata. | +| `getEvents`\* | `(request: GetEventsRequest) => Promise` | List parsed account events (jetton transfers, NFT moves, swaps, …) for an address. | +| `getMasterchainInfo`\* | `() => Promise` | Read the latest masterchain info — last seqno, shards, time. | + +#### ApiClientConfig + +Configuration accepted by [`NetworkConfig`](#networkconfig)'s `apiClient` — picks an [`ApiClient`](#apiclient) implementation (Toncenter / TonAPI) and supplies its endpoint URL plus optional API key. + +| Field | Type | Description | +| --- | --- | --- | +| `url` | `string` | Base URL of the indexer endpoint. Defaults to `'https://toncenter.com'` for mainnet, `'https://testnet.toncenter.com'` for testnet. | +| `key` | `string` | API key forwarded to the indexer for higher rate limits. | + +#### ApiClientToncenterConfig + +Configuration accepted by [`ApiClientToncenter`](#apiclienttoncenter) — endpoint, API key, request timeout, custom `fetch`, target network, and optional DNS-resolver override. + +| Field | Type | Description | +| --- | --- | --- | +| `dnsResolver` | `string` | Override the contract address used to resolve TON DNS records. Defaults to the network's standard root resolver. | +| `endpoint` | `string` | Base URL of the indexer endpoint. Defaults to the provider's mainnet/testnet URL based on `network`. | +| `apiKey` | `string` | API key forwarded to the indexer for higher rate limits. | +| `timeout` | `number` | Per-request timeout in milliseconds. Defaults to a provider-specific value. | +| `fetchApi` | `typeof fetch` | Custom `fetch` implementation. Defaults to the global `fetch`. | +| `network` | Network | [`Network`](#network) the client should target. Determines the default `endpoint` when one isn't supplied. | +| `disableNetworkSend` | `boolean` | When `true`, swallow `sendBoc` calls instead of broadcasting them — useful for local development and tests. | + +#### BaseApiClientConfig + +Configuration shared by every [`ApiClient`](#apiclient) subclass — endpoint, API key, request timeout, custom `fetch`, target network and a `disableNetworkSend` dev toggle. Accepted directly by [`ApiClientTonApi`](#apiclienttonapi); extended by [`ApiClientToncenterConfig`](#apiclienttoncenterconfig). + +| Field | Type | Description | +| --- | --- | --- | +| `endpoint` | `string` | Base URL of the indexer endpoint. Defaults to the provider's mainnet/testnet URL based on `network`. | +| `apiKey` | `string` | API key forwarded to the indexer for higher rate limits. | +| `timeout` | `number` | Per-request timeout in milliseconds. Defaults to a provider-specific value. | +| `fetchApi` | `typeof fetch` | Custom `fetch` implementation. Defaults to the global `fetch`. | +| `network` | Network | [`Network`](#network) the client should target. Determines the default `endpoint` when one isn't supplied. | +| `disableNetworkSend` | `boolean` | When `true`, swallow `sendBoc` calls instead of broadcasting them — useful for local development and tests. | + +#### GetApiClientOptions + +Options for [`getApiClient`](#getapiclient). + +| Field | Type | Description | +| --- | --- | --- | +| `network`\* | Network | Network whose configured [`ApiClient`](#apiclient) should be returned. | + +#### GetApiClientReturnType + +Return type of [`getApiClient`](#getapiclient). + +```ts +type GetApiClientReturnType = ApiClient; +``` + +#### TokenInfo + +Display metadata for a token (TON, jetton, or NFT) — name, symbol, image and animation as reported by the indexer. Surfaced as [`Jetton`](#jetton)'s `info` and [`NFT`](#nft)'s `info`. + +| Field | Type | Description | +| --- | --- | --- | +| `name` | `string` | Display name of the token | +| `description` | `string` | Human-readable description of the token | +| `image` | `TokenImage` | Token image in various sizes | +| `animation` | `TokenAnimation` | Animated media associated with the token | +| `symbol` | `string` | Ticker symbol of the token (e.g., "TON", "USDT") | + +### Connectors + +#### AddConnectorParameters + +Connector instance or factory accepted by [`addConnector`](#addconnector) — same shape used in [`AppKitConfig`](#appkitconfig)'s `connectors`. + +```ts +type AddConnectorParameters = ConnectorInput; +``` + +#### AddConnectorReturnType + +Return type of [`addConnector`](#addconnector) — call to remove the connector from AppKit. + +```ts +type AddConnectorReturnType = () => void; +``` + +#### ConnectParameters + +Parameters accepted by [`connect`](#connect). + +| Field | Type | Description | +| --- | --- | --- | +| `connectorId`\* | `string` | ID of the registered connector to drive the connection through (e.g., `'tonconnect'`). | + +#### ConnectReturnType + +Return type of [`connect`](#connect). + +```ts +type ConnectReturnType = void; +``` + +#### Connector + +Wallet connector contract — the protocol-specific bridge (TonConnect, embedded wallet, …) AppKit drives once you register it via [`AppKitConfig`](#appkitconfig)'s `connectors`. + +| Field | Type | Description | +| --- | --- | --- | +| `id`\* | `string` | Stable connector identifier, unique within an AppKit instance. | +| `type`\* | `string` | Protocol type (e.g. `'tonconnect'`). Multiple connectors can share the same type. | +| `metadata`\* | ConnectorMetadata | Display metadata (name, icon) shown in connect UIs. | +| `destroy`\* | `() => void` | Release any resources held by the connector. Call on app teardown. | +| `connectWallet`\* | (network?: Network) => Promise<void> | Initiate a wallet connection flow on the given network. | +| `disconnectWallet`\* | `() => Promise` | Disconnect the currently connected wallet, if any. | +| `getConnectedWallets`\* | () => WalletInterface[] | Wallets currently connected through this connector. | + +#### ConnectorFactory + +Factory that builds a [`Connector`](#connector) from [`ConnectorFactoryContext`](#connectorfactorycontext). AppKit calls it at registration time. + +```ts +type ConnectorFactory = (ctx: ConnectorFactoryContext) => Connector; +``` + +#### ConnectorFactoryContext + +Context that AppKit injects into a [`ConnectorFactory`](#connectorfactory) when building the connector at registration time. + +| Field | Type | Description | +| --- | --- | --- | +| `networkManager`\* | AppKitNetworkManager | Network manager the connector should use for client lookups and default-network reads. | +| `eventEmitter`\* | AppKitEmitter | Event emitter the connector should publish wallet/connection events to. | + +#### ConnectorInput + +Either a ready-made [`Connector`](#connector) or a [`ConnectorFactory`](#connectorfactory) that produces one — the value accepted by [`addConnector`](#addconnector) and [`AppKitConfig`](#appkitconfig)'s `connectors`. + +```ts +type ConnectorInput = Connector | ConnectorFactory; +``` + +#### ConnectorMetadata + +Display metadata for a [`Connector`](#connector), surfaced in connect UIs to help users pick the right wallet. + +| Field | Type | Description | +| --- | --- | --- | +| `name`\* | `string` | Human-readable connector name (e.g., `'TonConnect'`). | +| `iconUrl` | `string` | Optional URL of an icon shown next to the name. | + +#### DisconnectParameters + +Parameters accepted by [`disconnect`](#disconnect). + +| Field | Type | Description | +| --- | --- | --- | +| `connectorId`\* | `string` | ID of the registered connector whose wallet should be disconnected. | + +#### DisconnectReturnType + +Return type of [`disconnect`](#disconnect). + +```ts +type DisconnectReturnType = void; +``` + +#### GetConnectorByIdOptions + +Options for [`getConnectorById`](#getconnectorbyid). + +| Field | Type | Description | +| --- | --- | --- | +| `id`\* | `string` | ID of the connector to look up. | + +#### GetConnectorByIdReturnType + +Return type of [`getConnectorById`](#getconnectorbyid) — `undefined` when no connector with that id is registered. + +```ts +type GetConnectorByIdReturnType = Connector | undefined; +``` + +#### GetConnectorsReturnType + +Return type of [`getConnectors`](#getconnectors) — read-only view of the registered-connectors array. + +```ts +type GetConnectorsReturnType = readonly Connector[]; +``` + +#### TonConnectConnector + +[`Connector`](#connector) produced by [`createTonConnectConnector`](#createtonconnectconnector) — extends the base interface with the underlying `TonConnectUI` instance for advanced flows that need direct access (e.g., custom modals). + +| Field | Type | Description | +| --- | --- | --- | +| `id`\* | `string` | Stable connector identifier, unique within an AppKit instance. | +| `type`\* | `string` | Protocol type (e.g. `'tonconnect'`). Multiple connectors can share the same type. | +| `metadata`\* | ConnectorMetadata | Display metadata (name, icon) shown in connect UIs. | +| `destroy`\* | `() => void` | Release any resources held by the connector. Call on app teardown. | +| `connectWallet`\* | (network?: Network) => Promise<void> | Initiate a wallet connection flow on the given network. | +| `disconnectWallet`\* | `() => Promise` | Disconnect the currently connected wallet, if any. | +| `getConnectedWallets`\* | () => WalletInterface[] | Wallets currently connected through this connector. | +| `tonConnectUI`\* | `TonConnectUI \| null` | Underlying `TonConnectUI` instance — `null` during SSR or before the connector has been initialised. Apps that need to drive the modal directly (e.g. custom UI flows) can read this and call its methods. | + +#### TonConnectConnectorConfig + +Configuration accepted by [`createTonConnectConnector`](#createtonconnectconnector). + +| Field | Type | Description | +| --- | --- | --- | +| `id` | `string` | Connector ID. Defaults to [`TONCONNECT_DEFAULT_CONNECTOR_ID`](#tonconnect_default_connector_id) (`'tonconnect'`). Set this when you need to register multiple TonConnect-flavoured connectors side by side. | +| `metadata` | ConnectorMetadata | Display metadata override. Merged on top of TonConnect's default name and icon. | +| `tonConnectOptions` | `TonConnectUiCreateOptions` | Options forwarded to the underlying `TonConnectUI` constructor (manifest URL, etc.). Ignored when `tonConnectUI` is supplied. | +| `tonConnectUI` | `TonConnectUI` | Pre-built `TonConnectUI` instance to reuse. When set, the connector skips its own instantiation and `tonConnectOptions` is ignored. | + +#### WatchConnectorByIdParameters + +Parameters accepted by [`watchConnectorById`](#watchconnectorbyid). + +| Field | Type | Description | +| --- | --- | --- | +| `id`\* | `string` | ID of the connector to watch. | +| `onChange`\* | (connector: Connector \| undefined) => void | Callback invoked when the connector with the watched id is registered or unregistered — receives the connector itself, or `undefined` when none is registered under that id. | + +#### WatchConnectorByIdReturnType + +Return type of [`watchConnectorById`](#watchconnectorbyid) — call to stop receiving updates. + +```ts +type WatchConnectorByIdReturnType = () => void; +``` + +#### WatchConnectorsParameters + +Parameters accepted by [`watchConnectors`](#watchconnectors). + +| Field | Type | Description | +| --- | --- | --- | +| `onChange`\* | (connectors: readonly Connector[]) => void | Callback invoked when the list of registered connectors changes — receives the current list. | + +#### WatchConnectorsReturnType + +Return type of [`watchConnectors`](#watchconnectors) — call to stop receiving updates. + +```ts +type WatchConnectorsReturnType = () => void; +``` + +### Core + +#### AppKitConfig + +Constructor options for [`AppKit`](#appkit) — networks, connectors, providers and runtime flags. + +| Field | Type | Description | +| --- | --- | --- | +| `networks` | NetworkAdapters | Map of chain ID to [`NetworkConfig`](#networkconfig) (which holds the api-client setup). If omitted, AppKit defaults to mainnet only. | +| `connectors` | ConnectorInput[] | Wallet connectors registered at startup. | +| `defaultNetwork` | Network | Default network. | +| `providers` | ProviderInput[] | Providers registered at startup. | + +#### AppKitEmitter + +Strongly-typed event emitter accessed through `appKit.emitter`. `appKit.emitter.on(name, handler)` returns an unsubscribe function. + +```ts +type AppKitEmitter = EventEmitter; +``` + +#### AppKitEvents + +Map of every event name AppKit can emit to its payload type, used to type listeners on [`AppKitEmitter`](#appkitemitter). + +| Field | Type | Description | +| --- | --- | --- | +| `connector:added`\* | ConnectorAddedPayload | Fired by [`addConnector`](#addconnector) when a connector is registered with AppKit. | +| `connector:removed`\* | ConnectorRemovedPayload | Fired when a connector is unregistered from AppKit — typically by calling the unregister function returned from [`addConnector`](#addconnector). | +| `connector:wallets-updated`\* | ConnectorWalletsUpdatedPayload | Fired by a connector whenever its connected-wallets list changes (connect, disconnect, or account switch inside the wallet). | +| `wallets:updated`\* | { wallets: WalletInterface[] } | Fired by AppKit's wallet manager after re-aggregating connectors — `wallets` is the full current set. | +| `wallets:selection-changed`\* | `{ walletId: string \| null }` | Fired when the selected wallet changes — `walletId` is the new selection, or `null` when cleared. | +| `networks:updated`\* | `Record` | Fired by the network manager when a network's API client is registered or replaced via `setClient`. | +| `networks:default-changed`\* | DefaultNetworkChangedPayload | Fired by [`setDefaultNetwork`](#setdefaultnetwork) — carries the new default network, or `undefined` when the constraint was cleared. | +| `streaming:balance-update`\* | BalanceUpdate | Fired by a streaming provider when a watched address's TON balance changes. | +| `streaming:transactions`\* | TransactionsUpdate | Fired by a streaming provider when new transactions land for a watched address. | +| `streaming:jettons-update`\* | JettonUpdate | Fired by a streaming provider when a watched address's jetton holdings change. | +| `provider:registered`\* | BaseProviderUpdate | Fired by a DeFi manager when a provider is registered through it (carries the provider's id and kind). | +| `provider:default-changed`\* | BaseProviderUpdate | Fired by a DeFi manager when its default provider is set or cleared (carries the new default's id and kind). | + +#### BaseProviderUpdate + +Payload of `provider:registered` and `provider:default-changed` events — carries the affected provider's id and kind. + +| Field | Type | Description | +| --- | --- | --- | +| `providerId`\* | `string` | Stable id of the affected provider — same as the `providerId` it was registered with. | +| `type`\* | `string` | Provider-kind discriminator (e.g., `'swap'`, `'staking'`, `'onramp'`, `'crypto-onramp'`) — same as the provider's `type`. | + +#### ConnectorAddedPayload + +Payload of `connector:added` events — the connector that was just registered. + +| Field | Type | Description | +| --- | --- | --- | +| `connector`\* | Connector | The [`Connector`](#connector) that was just registered with AppKit. | + +#### ConnectorRemovedPayload + +Payload of `connector:removed` events — the connector that was just unregistered. + +| Field | Type | Description | +| --- | --- | --- | +| `connector`\* | Connector | The [`Connector`](#connector) that was just unregistered from AppKit (already torn down via `destroy()`). | + +#### ConnectorWalletsUpdatedPayload + +Payload of `connector:wallets-updated` events — fired by a connector when its connected-wallets list changes (connect, disconnect, or account switch inside the wallet). + +| Field | Type | Description | +| --- | --- | --- | +| `connectorId`\* | `string` | ID of the [`Connector`](#connector) whose wallets just changed. | +| `wallets`\* | WalletInterface[] | Wallets currently exposed by the connector — empty when the wallet was just disconnected. | + +#### DefaultNetworkChangedPayload + +Payload of `networks:default-changed` events — the new default network, or `undefined` when cleared. + +| Field | Type | Description | +| --- | --- | --- | +| `network`\* | Network \| undefined | New default network, or `undefined` when the constraint is cleared. | + +#### EventListener + +Listener callback signature accepted by [`EventEmitter`](#eventemitter)'s `on` — receives a [`KitEvent`](#kitevent) for the given event type and may return a Promise the emitter awaits. + +```ts +type EventListener = (event: KitEvent) => void | Promise; +``` + +#### EventPayload + +Generic event-payload constraint — an `object` that the typed event-name → payload map maps to. + +```ts +type EventPayload = object; +``` + +#### KitEvent + +Envelope every [`EventEmitter`](#eventemitter) listener receives — `type` is the event name, `payload` is the event-specific data, `source` identifies who emitted it, and `timestamp` is the wall-clock millisecond mark. + +| Field | Type | Description | +| --- | --- | --- | +| `type`\* | `string` | Event name (e.g., `'connector:wallets-updated'`). | +| `payload`\* | `T = any` | Event-specific payload — typed via the emitter's event-name → payload map. | +| `source` | `string` | Identifier of the component that emitted the event (connector id, manager name, etc.). Useful for filtering listeners. | +| `timestamp`\* | `number` | Wall-clock timestamp in milliseconds when the event was emitted. | + +#### SharedKitEvents + +Event-name → payload map shared between AppKit and walletkit. AppKit extends it with its own connector, wallet and network events to type [`AppKitEmitter`](#appkitemitter). + +| Field | Type | Description | +| --- | --- | --- | +| `streaming:balance-update`\* | BalanceUpdate | Fired by a streaming provider when a watched address's TON balance changes. | +| `streaming:transactions`\* | TransactionsUpdate | Fired by a streaming provider when new transactions land for a watched address. | +| `streaming:jettons-update`\* | JettonUpdate | Fired by a streaming provider when a watched address's jetton holdings change. | +| `provider:registered`\* | BaseProviderUpdate | Fired by a DeFi manager when a provider is registered through it (carries the provider's id and kind). | +| `provider:default-changed`\* | BaseProviderUpdate | Fired by a DeFi manager when its default provider is set or cleared (carries the new default's id and kind). | + +### Crypto Onramp + +#### CreateCryptoOnrampDepositOptions + +Options for [`createCryptoOnrampDeposit`](#createcryptoonrampdeposit) — extends [`CryptoOnrampDepositParams`](#cryptoonrampdepositparams) with an optional provider override. + +| Field | Type | Description | +| --- | --- | --- | +| `quote`\* | CryptoOnrampQuote<TQuoteMetadata = unknown> | Quote to execute the deposit against (contains recipientAddress and provider metadata) | +| `refundAddress`\* | `string` | Address to refund the crypto to in case of failure | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerId` | `string` | Provider to create the deposit through. Defaults to `quote.providerId`, then to the default provider. | + +#### CreateCryptoOnrampDepositReturnType + +Return type of [`createCryptoOnrampDeposit`](#createcryptoonrampdeposit). + +```ts +type CreateCryptoOnrampDepositReturnType = Promise; +``` + +#### CryptoOnrampDeposit + +Deposit details returned by a crypto onramp provider. + +The user must send `amount` of `sourceCurrencyAddress` to `address` on `sourceChain` +to complete the onramp. The provider then delivers the target crypto to the user's TON address. + +| Field | Type | Description | +| --- | --- | --- | +| `depositId`\* | `string` | Deposit id | +| `address`\* | `string` | Deposit address on the source chain | +| `amount`\* | `string` | Exact amount of source crypto the user must send | +| `sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | +| `sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:42161'). | +| `memo` | `string` | Optional memo / tag required by some chains (e.g. XRP, TON comment) | +| `expiresAt` | `number` | Unix timestamp (ms) after which the deposit offer is no longer valid | +| `chainWarning` | `string` | Chain-specific warning to show the user (e.g. "send only on Solana") | +| `providerId`\* | `string` | Identifier of the provider that issued this deposit | + +#### CryptoOnrampDepositParams + +Parameters for creating a crypto onramp deposit. + +The recipient is taken from `quote.recipientAddress` set at quote time. + +| Field | Type | Description | +| --- | --- | --- | +| `quote`\* | CryptoOnrampQuote<TQuoteMetadata = unknown> | Quote to execute the deposit against (contains recipientAddress and provider metadata) | +| `refundAddress`\* | `string` | Address to refund the crypto to in case of failure | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | + +#### CryptoOnrampProviderInterface + +Interface that all crypto onramp providers must implement + +| Field | Type | Description | +| --- | --- | --- | +| `type`\* | `'crypto-onramp'` | Provider kind discriminator pinned to `'crypto-onramp'` so [`registerProvider`](#registerprovider) routes it to the crypto-onramp manager. | +| `providerId`\* | `string` | Unique identifier for the provider | +| `getMetadata`\* | () => CryptoOnrampProviderMetadata | Get static metadata for the provider (display name, logo, url). | +| `getQuote`\* | (params: CryptoOnrampQuoteParams<TQuoteOptions>) => Promise<CryptoOnrampQuote> | Get a quote for onramping from another crypto asset into a TON asset | +| `createDeposit`\* | (params: CryptoOnrampDepositParams<TDepositOptions>) => Promise<CryptoOnrampDeposit> | Create a deposit for a previously obtained quote | +| `getStatus`\* | (params: CryptoOnrampStatusParams) => Promise<CryptoOnrampStatus> | Get the status of a deposit | +| `getSupportedNetworks`\* | () => Network[] | Networks this provider can operate on. Consumers should check before calling provider methods. Implementations may return a static list or compute it dynamically (e.g. from runtime config). | + +#### CryptoOnrampProviderMetadata + +Static metadata for a crypto-onramp provider. + +| Field | Type | Description | +| --- | --- | --- | +| `name`\* | `string` | Human-readable provider name (e.g. 'Swaps.xyz') | +| `logo` | `string` | URL to the provider's logo image | +| `url` | `string` | URL to the provider's website | +| `isRefundAddressRequired` | `boolean` | Whether this provider requires a refund address on the source chain. When true, the UI must collect a refund address before creating a deposit. | +| `isReversedAmountSupported` | `boolean` | Whether this provider supports reversed (target-amount) quotes. When false, the UI should hide the direction toggle and only allow source-amount input. | + +#### CryptoOnrampProviderMetadataOverride + +Used in provider configuration to override fields of the provider's metadata. + +| Field | Type | Description | +| --- | --- | --- | +| `name` | `string` | Override the provider's display name | +| `logo` | `string` | Override the provider's logo URL | +| `url` | `string` | Override the provider's website URL | + +#### CryptoOnrampQuote + +Crypto onramp quote response with pricing information + +| Field | Type | Description | +| --- | --- | --- | +| `sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | +| `sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:42161'). | +| `targetCurrencyAddress`\* | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | +| `sourceAmount`\* | `string` | Amount of source crypto to send | +| `targetAmount`\* | `string` | Amount of target crypto to receive | +| `rate`\* | `string` | Exchange rate (amount of target per 1 unit of source) | +| `recipientAddress`\* | `string` | TON address that will receive the target crypto | +| `providerId`\* | `string` | Identifier of the crypto onramp provider | +| `metadata` | `TMetadata = unknown` | Provider-specific metadata for the quote (e.g. raw response needed to execute) | + +#### CryptoOnrampQuoteParams + +Parameters for requesting a crypto-to-crypto onramp quote. + +The target network is always TON, so only the source side is parameterised. + +| Field | Type | Description | +| --- | --- | --- | +| `amount`\* | `string` | Amount to onramp (either source or target crypto, depending on isSourceAmount) | +| `sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | +| `sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | +| `targetCurrencyAddress`\* | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | +| `recipientAddress`\* | `string` | TON address that will receive the target crypto | +| `refundAddress` | `string` | Refund address for the source crypto | +| `isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | + +#### CryptoOnrampStatus + +Final state of a crypto-onramp deposit returned by [`getCryptoOnrampStatus`](#getcryptoonrampstatus) — `'success'` (delivered to the recipient), `'pending'` (still in flight), or `'failed'` (provider could not complete the deposit). + +```ts +type CryptoOnrampStatus = 'success' | 'pending' | 'failed'; +``` + +#### CryptoOnrampStatusParams + +Parameters accepted by [`getCryptoOnrampStatus`](#getcryptoonrampstatus) — identifies a previously created deposit and the provider that issued it. + +| Field | Type | Description | +| --- | --- | --- | +| `depositId`\* | `string` | Deposit id | +| `providerId`\* | `string` | Identifier of the provider that issued this deposit | + +#### GetCryptoOnrampProviderOptions + +Options for [`getCryptoOnrampProvider`](#getcryptoonrampprovider). + +| Field | Type | Description | +| --- | --- | --- | +| `id` | `string` | Provider ID to look up. When omitted, returns the registered default provider. | + +#### GetCryptoOnrampProviderReturnType + +Return type of [`getCryptoOnrampProvider`](#getcryptoonrampprovider). + +```ts +type GetCryptoOnrampProviderReturnType = CryptoOnrampProviderInterface; +``` + +#### GetCryptoOnrampProvidersReturnType + +Return type of [`getCryptoOnrampProviders`](#getcryptoonrampproviders). + +```ts +type GetCryptoOnrampProvidersReturnType = CryptoOnrampProviderInterface[]; +``` + +#### GetCryptoOnrampQuoteOptions + +Options for [`getCryptoOnrampQuote`](#getcryptoonrampquote) — extends [`CryptoOnrampQuoteParams`](#cryptoonrampquoteparams) with an optional provider override. + +| Field | Type | Description | +| --- | --- | --- | +| `amount`\* | `string` | Amount to onramp (either source or target crypto, depending on isSourceAmount) | +| `sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | +| `sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | +| `targetCurrencyAddress`\* | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | +| `recipientAddress`\* | `string` | TON address that will receive the target crypto | +| `refundAddress` | `string` | Refund address for the source crypto | +| `isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerId` | `string` | Provider to quote against. Defaults to the registered default provider. | + +#### GetCryptoOnrampQuoteReturnType + +Return type of [`getCryptoOnrampQuote`](#getcryptoonrampquote). + +```ts +type GetCryptoOnrampQuoteReturnType = Promise; +``` + +#### GetCryptoOnrampStatusOptions + +Options for [`getCryptoOnrampStatus`](#getcryptoonrampstatus) — extends [`CryptoOnrampStatusParams`](#cryptoonrampstatusparams) with an optional provider override. + +| Field | Type | Description | +| --- | --- | --- | +| `depositId`\* | `string` | Deposit id | +| `providerId`\* | `string` | Identifier of the provider that issued this deposit | + +#### GetCryptoOnrampStatusReturnType + +Return type of [`getCryptoOnrampStatus`](#getcryptoonrampstatus). + +```ts +type GetCryptoOnrampStatusReturnType = Promise; +``` + +#### LayerswapProviderConfig + +Configuration accepted by [`createLayerswapProvider`](#createlayerswapprovider). + +| Field | Type | Description | +| --- | --- | --- | +| `apiKey` | `string` | Optional API key. Forwarded as `X-LS-APIKEY` when provided. | +| `apiUrl` | `string` | Override the base API URL. Defaults to https://api.layerswap.io/api/v2 | + +#### LayerswapQuoteMetadata + +Provider-specific metadata returned on a [`CryptoOnrampQuote`](#cryptoonrampquote)'s `metadata` from Layerswap — carries the swap id and deposit action that [`createCryptoOnrampDeposit`](#createcryptoonrampdeposit) reads to build the deposit. + +| Field | Type | Description | +| --- | --- | --- | +| `swapId`\* | `string` | Layerswap swap id created at quote time and reused by `createDeposit` / `getStatus`. | +| `depositAddress`\* | `string` | Pre-computed deposit address on the source chain that the user must send funds to. | +| `sourceAmountBaseUnits`\* | `string` | Source-chain amount the user must send, in raw base units (e.g., wei). | +| `targetAmountBaseUnits`\* | `string` | Target-chain amount the user receives, in raw base units (e.g., nanotons). | + +#### SwapsXyzProviderConfig + +Configuration accepted by [`createSwapsXyzProvider`](#createswapsxyzprovider). + +| Field | Type | Description | +| --- | --- | --- | +| `apiKey`\* | `string` | API key issued by swaps.xyz (passed as `x-api-key`) | +| `apiUrl` | `string` | Override the base API URL. Defaults to https://api-v2.swaps.xyz/api | +| `defaultSender` | `string` | EVM address used as `sender` on getAction requests. Required by the API even for deposit flows where the actual payer is unknown. Defaults to a null address when omitted. | + +#### SwapsXyzQuoteMetadata + +Provider-specific metadata returned on a [`CryptoOnrampQuote`](#cryptoonrampquote)'s `metadata` from swaps.xyz — carries the resolved action and bridge route that [`createCryptoOnrampDeposit`](#createcryptoonrampdeposit) needs. + +| Field | Type | Description | +| --- | --- | --- | +| `sender`\* | `string` | EVM sender address swaps.xyz was quoted for. Required when later calling `createDeposit`. | +| `response`\* | `SwapsXyzGetActionResponse` | Raw `getAction` response cached at quote time so `createDeposit` doesn't need an extra round-trip. | + +#### SwapsXyzQuoteOptions + +swaps.xyz-specific options forwarded through `providerOptions` on [`CryptoOnrampQuoteParams`](#cryptoonrampquoteparams). + +| Field | Type | Description | +| --- | --- | --- | +| `slippageBps` | `number` | Slippage tolerance in basis points (0-10000). Defaults to 100 (1%). | + +#### WatchCryptoOnrampProvidersParameters + +Parameters accepted by [`watchCryptoOnrampProviders`](#watchcryptoonrampproviders). + +| Field | Type | Description | +| --- | --- | --- | +| `onChange`\* | `() => void` | Callback fired whenever a crypto-onramp provider is registered or the default crypto-onramp provider changes. | + +#### WatchCryptoOnrampProvidersReturnType + +Return type of [`watchCryptoOnrampProviders`](#watchcryptoonrampproviders) — call to stop receiving updates. + +```ts +type WatchCryptoOnrampProvidersReturnType = () => void; +``` + +### DeFi + +#### DefiManagerAPI + +Shape every DeFi domain manager (swap, staking, onramp, crypto-onramp) satisfies — provider registration, default-provider selection and lookups. Mostly relevant when authoring a new domain manager. + +| Field | Type | Description | +| --- | --- | --- | +| `createFactoryContext`\* | () => ProviderFactoryContext | Build a fresh [`ProviderFactoryContext`](#providerfactorycontext) the manager hands to provider factories at registration time. | +| `registerProvider`\* | (provider: ProviderInput<T>) => void | Register a new provider. If a provider with the same id is already registered, it is replaced. | +| `removeProvider`\* | `(provider: T) => void` | Remove a previously registered provider. No-op if the provider was not registered. | +| `setDefaultProvider`\* | `(providerId: string) => void` | Set the default provider | +| `getProvider`\* | `(providerId?: string) => T` | Get a registered provider | +| `getProviders`\* | `() => T[]` | Get all registered providers. The returned array keeps a stable reference until the provider list changes. | +| `hasProvider`\* | `(providerId: string) => boolean` | Check if a provider is registered | + +#### DefiProvider + +Base interface implemented by every DeFi provider (swap, staking, onramp, crypto-onramp) — exposes `providerId`, `type` and `getSupportedNetworks`. Domain-specific provider interfaces extend this with quote/build/status methods. + +| Field | Type | Description | +| --- | --- | --- | +| `type`\* | DefiProviderType | Provider kind discriminator narrowed to the DeFi-domain literals so the right manager picks it up at registration time. | +| `getSupportedNetworks`\* | () => Network[] | Networks this provider can operate on. Consumers should check before calling provider methods. Implementations may return a static list or compute it dynamically (e.g. from runtime config). | +| `providerId`\* | `string` | Stable provider identifier, unique within the manager that registered it. | + +#### DefiProviderType + +Discriminator that tags every [`DefiProvider`](#defiprovider) with its kind — `'swap'`, `'staking'`, `'onramp'`, or `'crypto-onramp'`. Used by [`registerProvider`](#registerprovider) to dispatch to the right manager. + +```ts +type DefiProviderType = 'swap' | 'staking' | 'onramp' | 'crypto-onramp'; +``` + +#### ProviderFactoryContext + +Context that AppKit's DeFi managers inject into a [`ProviderInput`](#providerinput) factory at registration time — gives the provider access to AppKit's network manager and event emitter. + +| Field | Type | Description | +| --- | --- | --- | +| `networkManager`\* | `NetworkManager` | Network manager the provider should use for client lookups and default-network reads. | +| `eventEmitter`\* | EventEmitter<Events = SharedKitEvents> | Event emitter the provider should publish its events to. | + +#### ProviderInput + +Either a ready-made DeFi/onramp provider instance or a factory that produces one — the value accepted by [`AppKitConfig`](#appkitconfig)'s `providers` and [`registerProvider`](#registerprovider). + +```ts +type ProviderInput = T | ProviderFactory; +``` + +#### RegisterProviderOptions + +Provider instance or factory accepted by [`registerProvider`](#registerprovider) — same shape used in [`AppKitConfig`](#appkitconfig)'s `providers`. AppKit dispatches it to the right manager based on `provider.type` (`'swap'`, `'staking'`, `'onramp'`, `'crypto-onramp'`). + +```ts +type RegisterProviderOptions = ProviderInput; +``` + +### Jettons + +#### CreateTransferJettonTransactionParameters + +Parameters accepted by [`createTransferJettonTransaction`](#createtransferjettontransaction) and [`transferJetton`](#transferjetton). + +| Field | Type | Description | +| --- | --- | --- | +| `jettonAddress`\* | UserFriendlyAddress | Jetton master contract address being transferred. | +| `recipientAddress`\* | UserFriendlyAddress | Recipient who should receive the jettons. | +| `amount`\* | `string` | Amount in jetton units as a human-readable decimal string (e.g., `"1.5"`). | +| `jettonDecimals`\* | `number` | Decimals declared by the jetton master. Used to convert `amount` into raw smallest units. | +| `comment` | `string` | Optional human-readable comment attached to the transfer. | + +#### CreateTransferJettonTransactionReturnType + +Return type of [`createTransferJettonTransaction`](#createtransferjettontransaction). + +```ts +type CreateTransferJettonTransactionReturnType = TransactionRequest; +``` + +#### GetJettonBalanceOptions + +Options for [`getJettonBalance`](#getjettonbalance). + +| Field | Type | Description | +| --- | --- | --- | +| `jettonAddress`\* | UserFriendlyAddress | Jetton master contract address (the token, not the user's wallet for it). | +| `ownerAddress`\* | UserFriendlyAddress | Owner of the jetton wallet — typically the connected user's address. | +| `jettonDecimals`\* | `number` | Decimals declared by the jetton master. Used to format the raw balance into a human-readable string. | +| `network` | Network | Network to read the balance from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +#### GetJettonBalanceReturnType + +Return type of [`getJettonBalance`](#getjettonbalance). + +```ts +type GetJettonBalanceReturnType = TokenAmount; +``` + +#### GetJettonInfoOptions + +Options for [`getJettonInfo`](#getjettoninfo). + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | UserFriendlyAddress | Jetton master contract address whose metadata is being fetched. | +| `network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +#### GetJettonInfoReturnType + +Return type of [`getJettonInfo`](#getjettoninfo) — `null` when the indexer has no record for that master address. + +```ts +type GetJettonInfoReturnType = JettonInfo | null; +``` + +#### GetJettonWalletAddressOptions + +Options for [`getJettonWalletAddress`](#getjettonwalletaddress). + +| Field | Type | Description | +| --- | --- | --- | +| `jettonAddress`\* | UserFriendlyAddress | Jetton master contract address. | +| `ownerAddress`\* | UserFriendlyAddress | Owner whose jetton wallet should be derived. | +| `network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +#### GetJettonWalletAddressReturnType + +Return type of [`getJettonWalletAddress`](#getjettonwalletaddress). + +```ts +type GetJettonWalletAddressReturnType = UserFriendlyAddress; +``` + +#### GetJettonsByAddressOptions + +Options for [`getJettonsByAddress`](#getjettonsbyaddress). + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `network` | Network | Network to read the jettons from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `limit` | `number` | Maximum number of jettons to return. | +| `offset` | `number` | Number of jettons to skip before returning results — used for pagination. | + +#### GetJettonsByAddressReturnType + +Return type of [`getJettonsByAddress`](#getjettonsbyaddress). + +```ts +type GetJettonsByAddressReturnType = JettonsResponse; +``` + +#### GetJettonsOptions + +Options for [`getJettons`](#getjettons). + +| Field | Type | Description | +| --- | --- | --- | +| `network` | Network | Network to read jettons from. Defaults to the selected wallet's network. | +| `limit` | `number` | Maximum number of jettons to return. | +| `offset` | `number` | Number of jettons to skip before returning results — used for pagination. | + +#### GetJettonsReturnType + +Return type of [`getJettons`](#getjettons) — `null` when no wallet is currently selected. + +```ts +type GetJettonsReturnType = JettonsResponse | null; +``` + +#### Jetton + +Fungible TEP-74 token held in the user's TON wallet — carries the master contract address, the user's jetton-wallet address, current balance, and token metadata. + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | UserFriendlyAddress | The jetton master contract address (the token itself). | +| `walletAddress`\* | UserFriendlyAddress | The owner's jetton-wallet contract address — the per-owner contract that actually holds this balance. | +| `balance`\* | TokenAmount | The current jetton balance | +| `info`\* | TokenInfo | Information about the token | +| `decimalsNumber` | `number` | The number of decimal places used by the token | +| `isVerified`\* | `boolean` | Indicates if the jetton is verified | +| `prices`\* | `JettonPrice[]` | Current prices of the jetton in various currencies | +| `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the jetton | + +#### JettonInfo + +Token metadata for a jetton master — name, symbol, decimals, image, and verification status as reported by the indexer. + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | `string` | Jetton master contract address. | +| `name`\* | `string` | Display name of the jetton (e.g., `"Tether USD"`). | +| `symbol`\* | `string` | Ticker symbol (e.g., `"USDT"`). | +| `description`\* | `string` | Free-form description set by the issuer. | +| `decimals` | `number` | Number of decimal places used to format raw amounts (e.g., `6` for USDT). | +| `totalSupply` | `string` | Total supply in raw smallest units. | +| `image` | `string` | URL of the jetton's image. | +| `image_data` | `string` | Inline image data (Base64) when no `image` URL is published. | +| `uri` | `string` | Off-chain metadata URI (TEP-64). | +| `verification` | JettonVerification | Verification status reported by the indexer. | +| `metadata` | `Record` | Additional indexer-supplied metadata that doesn't fit the canonical fields. | + +#### JettonUpdate + +Update payload delivered to [`watchJettons`](#watchjettons) / [`watchJettonsByAddress`](#watchjettonsbyaddress) subscribers when the watched owner's jetton balance changes. + +| Field | Type | Description | +| --- | --- | --- | +| `type`\* | `'jettons'` | The update type field | +| `masterAddress`\* | UserFriendlyAddress | The master jetton contract address | +| `walletAddress`\* | UserFriendlyAddress | The jetton wallet contract address | +| `ownerAddress`\* | UserFriendlyAddress | The owner of the jetton wallet | +| `rawBalance`\* | TokenAmount | Balance in raw smallest units (e.g. nano) | +| `decimals` | `number` | Decimals mapped from metadata if available | +| `balance` | `string` | Human readable formatted balance if decimals are known | +| `status`\* | StreamingUpdateStatus | The finality of the update | + +#### JettonVerification + +Verification metadata reported by the indexer for a [`JettonInfo`](#jettoninfo) — `verified` flag plus optional verifier source. + +| Field | Type | Description | +| --- | --- | --- | +| `verified`\* | `boolean` | `true` when the indexer has verified this jetton against an allow-list. | +| `source` | `'toncenter' \| 'community' \| 'manual'` | Origin of the verification claim. | +| `warnings` | `string[]` | Free-form warnings the UI should surface (e.g., scam indicators). | + +#### JettonsResponse + +Response payload of [`getJettons`](#getjettons) / [`getJettonsByAddress`](#getjettonsbyaddress) — the list of [`Jetton`](#jetton)s plus the address book that resolves raw addresses inside it. + +| Field | Type | Description | +| --- | --- | --- | +| `addressBook`\* | AddressBook | Address book mapping | +| `jettons`\* | Jetton[] | List of Jettons | + +#### TransferJettonParameters + +Parameters accepted by [`transferJetton`](#transferjetton) — same shape as [`CreateTransferJettonTransactionParameters`](#createtransferjettontransactionparameters). + +```ts +type TransferJettonParameters = CreateTransferJettonTransactionParameters; +``` + +#### TransferJettonReturnType + +Return type of [`transferJetton`](#transferjetton). + +```ts +type TransferJettonReturnType = SendTransactionResponse; +``` + +#### WatchJettonsByAddressOptions + +Options for [`watchJettonsByAddress`](#watchjettonsbyaddress). + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `onChange`\* | (update: JettonUpdate) => void | Callback fired on every jetton-balance update from the streaming provider. | +| `network` | Network | Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +#### WatchJettonsByAddressReturnType + +Return type of [`watchJettonsByAddress`](#watchjettonsbyaddress) — call to stop receiving updates. + +```ts +type WatchJettonsByAddressReturnType = () => void; +``` + +#### WatchJettonsOptions + +Options for [`watchJettons`](#watchjettons). + +| Field | Type | Description | +| --- | --- | --- | +| `onChange`\* | (update: JettonUpdate) => void | Callback fired on every jetton-balance update from the streaming provider. | +| `network` | Network | Network to watch on. Defaults to the selected wallet's network. | + +#### WatchJettonsReturnType + +Return type of [`watchJettons`](#watchjettons) — call to stop receiving updates. + +```ts +type WatchJettonsReturnType = () => void; +``` + +### NFTs + +#### CreateTransferNftTransactionParameters + +Parameters accepted by [`createTransferNftTransaction`](#createtransfernfttransaction) and [`transferNft`](#transfernft). + +| Field | Type | Description | +| --- | --- | --- | +| `nftAddress`\* | UserFriendlyAddress | NFT contract address to transfer. | +| `recipientAddress`\* | UserFriendlyAddress | New owner address. | +| `amount` | `string` | Amount of TON to attach to the transfer for gas. Defaults to AppKit's NFT gas-fee constant when omitted. | +| `comment` | `string` | Optional human-readable comment attached to the transfer. | + +#### CreateTransferNftTransactionReturnType + +Return type of [`createTransferNftTransaction`](#createtransfernfttransaction). + +```ts +type CreateTransferNftTransactionReturnType = TransactionRequest; +``` + +#### GetNftOptions + +Options for [`getNft`](#getnft). + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | UserFriendlyAddress \| Address | NFT contract address — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +#### GetNftReturnType + +Return type of [`getNft`](#getnft) — `null` when the indexer has no record for that address. + +```ts +type GetNftReturnType = NFT | null; +``` + +#### GetNftsByAddressOptions + +Options for [`getNftsByAddress`](#getnftsbyaddress). + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | UserFriendlyAddress \| Address | Owner address — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `network` | Network | Network to read NFTs from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `limit` | `number` | Maximum number of NFTs to return. | +| `offset` | `number` | Number of NFTs to skip before returning results — used for pagination. | + +#### GetNftsByAddressReturnType + +Return type of [`getNftsByAddress`](#getnftsbyaddress). + +```ts +type GetNftsByAddressReturnType = NFTsResponse; +``` + +#### GetNftsOptions + +Options for [`getNfts`](#getnfts). + +| Field | Type | Description | +| --- | --- | --- | +| `network` | Network | Network to read NFTs from. Defaults to the selected wallet's network. | +| `limit` | `number` | Maximum number of NFTs to return. | +| `offset` | `number` | Number of NFTs to skip before returning results — used for pagination. | + +#### GetNftsReturnType + +Return type of [`getNfts`](#getnfts) — `null` when no wallet is currently selected. + +```ts +type GetNftsReturnType = NFTsResponse | null; +``` + +#### NFT + +Non-fungible TEP-62 token held in the user's TON wallet — carries the contract address, optional collection link, owner, sale state, and on-chain metadata. + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | UserFriendlyAddress | Contract address of the NFT item | +| `index` | `string` | Index of the item within its collection | +| `info` | TokenInfo | Display information about the NFT (name, description, images) | +| `attributes` | NFTAttribute[] | Custom attributes/traits of the NFT (e.g., rarity, properties) | +| `collection` | NFTCollection | Information about the collection this item belongs to | +| `auctionContractAddress` | UserFriendlyAddress | Address of the auction contract, if the NFT is being auctioned | +| `codeHash` | Hex | Hash of the NFT smart contract code | +| `dataHash` | Hex | Hash of the NFT's on-chain data | +| `isInited` | `boolean` | Whether the NFT contract has been initialized | +| `isSoulbound` | `boolean` | Whether the NFT is soulbound (non-transferable) | +| `isOnSale` | `boolean` | Whether the NFT is currently listed for sale | +| `ownerAddress` | UserFriendlyAddress | Current owner address of the NFT | +| `realOwnerAddress` | UserFriendlyAddress | Real owner address when NFT is on sale (sale contract becomes temporary owner) | +| `saleContractAddress` | UserFriendlyAddress | Address of the sale contract, if the NFT is listed for sale | +| `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the NFT. | + +#### NFTAttribute + +Single trait of an [`NFT`](#nft) — `traitType` names the category (e.g., `"Background"`), `value` carries the trait's value (e.g., `"Blue"`). + +| Field | Type | Description | +| --- | --- | --- | +| `traitType` | `string` | Category or type of the trait (e.g., "Background", "Eyes") | +| `displayType` | `string` | Indexer-supplied hint for how the attribute should be rendered. Optional and indexer-specific. | +| `value` | `string` | Value of the attribute (e.g., "Blue", "Rare") | + +#### NFTCollection + +NFT collection (TEP-62) — surfaced as [`NFT`](#nft)'s `collection` and carries the collection's name, image, owner and minting cursor. + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | UserFriendlyAddress | The blockchain address of the NFT collection contract | +| `name` | `string` | The name of the NFT collection | +| `image` | `TokenImage` | The image representing the NFT collection | +| `description` | `string` | A brief description of the NFT collection | +| `nextItemIndex` | `string` | The index value for the next item to be minted in the collection | +| `codeHash` | Hex | The hash of the collection's smart contract code | +| `dataHash` | Hex | The hash of the collection's data in the blockchain | +| `ownerAddress` | UserFriendlyAddress | The blockchain address of the collection owner | +| `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the NFT collection | + +#### NFTsResponse + +Response payload of [`getNfts`](#getnfts) / [`getNftsByAddress`](#getnftsbyaddress) — the list of [`NFT`](#nft)s plus an address book that resolves raw addresses inside it. + +| Field | Type | Description | +| --- | --- | --- | +| `addressBook` | AddressBook | Address book entries related to the NFTs | +| `nfts`\* | NFT[] | List of NFTs | + +#### TransferNftParameters + +Parameters accepted by [`transferNft`](#transfernft) — same shape as [`CreateTransferNftTransactionParameters`](#createtransfernfttransactionparameters). + +```ts +type TransferNftParameters = CreateTransferNftTransactionParameters; +``` + +#### TransferNftReturnType + +Return type of [`transferNft`](#transfernft). + +```ts +type TransferNftReturnType = SendTransactionResponse; +``` + +### Networks + +#### GetBlockNumberOptions + +Options for [`getBlockNumber`](#getblocknumber). + +| Field | Type | Description | +| --- | --- | --- | +| `network` | Network | Network to query. Defaults to mainnet when omitted. | + +#### GetBlockNumberReturnType + +Return type of [`getBlockNumber`](#getblocknumber). + +```ts +type GetBlockNumberReturnType = number; +``` + +#### GetDefaultNetworkReturnType + +Return type of [`getDefaultNetwork`](#getdefaultnetwork) — `undefined` when no default has been set (apps may operate on any registered network). + +```ts +type GetDefaultNetworkReturnType = Network | undefined; +``` + +#### GetNetworkReturnType + +Return type of [`getNetwork`](#getnetwork) — `null` when no wallet is currently selected. + +```ts +type GetNetworkReturnType = Network | null; +``` + +#### GetNetworksReturnType + +Return type of [`getNetworks`](#getnetworks). + +```ts +type GetNetworksReturnType = Network[]; +``` + +#### HasStreamingProviderReturnType + +Return type of [`hasStreamingProvider`](#hasstreamingprovider). + +```ts +type HasStreamingProviderReturnType = boolean; +``` + +#### Network + +TON blockchain network identifier. + +| Field | Type | Description | +| --- | --- | --- | +| `chainId`\* | `string` | Chain ID of the network (e.g., "-239" for mainnet, "-3" for testnet) | + +#### NetworkAdapters + +Multi-network configuration keyed by chain ID — each entry maps a chain ID (e.g. `Network.mainnet().chainId`) to its own [`NetworkConfig`](#networkconfig) carrying the api-client setup. + +```ts +type NetworkAdapters = { + [key: string]: NetworkConfig | undefined; +}; +``` + +#### NetworkConfig + +Network configuration for a specific chain + +| Field | Type | Description | +| --- | --- | --- | +| `apiClient` | ApiClientConfig \| ApiClient | API client configuration or instance | + +#### SetDefaultNetworkParameters + +Parameters accepted by [`setDefaultNetwork`](#setdefaultnetwork). + +| Field | Type | Description | +| --- | --- | --- | +| `network`\* | Network \| undefined | Network to enforce on new wallet connections. Pass `undefined` to allow any registered network. | + +#### SetDefaultNetworkReturnType + +Return type of [`setDefaultNetwork`](#setdefaultnetwork). + +```ts +type SetDefaultNetworkReturnType = void; +``` + +#### TonWalletKitOptions + +Walletkit-side options shape consumed by [`KitNetworkManager`](#kitnetworkmanager)'s constructor — chiefly the `networks` map keyed by chain ID. [`AppKit`](#appkit) constructs the manager for you, so apps rarely instantiate this directly. + +| Field | Type | Description | +| --- | --- | --- | +| `walletManifest` | `WalletInfo` | TonConnect wallet manifest published by the dApp. Required for the wallet to recognize the integration. | +| `deviceInfo` | `DeviceInfo` | Device fingerprint forwarded with TonConnect requests so wallets can recognize the host. | +| `sessionManager` | `TONConnectSessionManager` | Custom session manager implementation. If not provided, TONConnectStoredSessionManager will be used. | +| `networks` | NetworkAdapters | Network configuration | +| `bridge` | `BridgeConfig` | Bridge settings | +| `storage` | `StorageConfig \| StorageAdapter` | Storage settings | +| `validation` | `{ strictMode?: boolean; allowUnknownWalletVersions?: boolean; }` | Validation settings | +| `eventProcessor` | `EventProcessorConfig` | Event processor settings | +| `analytics` | `AnalyticsManagerOptions & { enabled?: boolean; }` | Analytics manager options merged with an `enabled` toggle. Off by default. | +| `dev` | `{ disableNetworkSend?: boolean; disableManifestDomainCheck?: boolean; }` | Diagnostic toggles useful during local development. Should not be set in production builds. | + +#### WatchDefaultNetworkParameters + +Parameters accepted by [`watchDefaultNetwork`](#watchdefaultnetwork). + +| Field | Type | Description | +| --- | --- | --- | +| `onChange`\* | (network: Network \| undefined) => void | Callback fired whenever [`setDefaultNetwork`](#setdefaultnetwork) updates the default — receives the new value (or `undefined` when cleared). | + +#### WatchDefaultNetworkReturnType + +Return type of [`watchDefaultNetwork`](#watchdefaultnetwork) — call to stop receiving updates. + +```ts +type WatchDefaultNetworkReturnType = () => void; +``` + +#### WatchNetworksParameters + +Parameters accepted by [`watchNetworks`](#watchnetworks). + +| Field | Type | Description | +| --- | --- | --- | +| `onChange`\* | (networks: Network[]) => void | Callback fired whenever the configured-networks list changes — receives the latest snapshot. | + +#### WatchNetworksReturnType + +Return type of [`watchNetworks`](#watchnetworks) — call to stop receiving updates. + +```ts +type WatchNetworksReturnType = () => void; +``` + +### Primitives + +#### Base64String + +Base64-encoded byte string — used for transaction payloads, BoCs, signatures, and other opaque binary blobs that travel through TonConnect and the indexer APIs. + +```ts +type Base64String = string & { + readonly [base64StringBrand]: never; +}; +``` + +#### ExtraCurrencies + +Map of extra-currency ids to raw amounts attached to a transaction message — TON's mechanism for transferring non-jetton native tokens (e.g., wrapped or testnet currencies). Keys are the extra-currency ids defined by the masterchain configuration. + +```ts +type ExtraCurrencies = { + [key: string]: string; +}; +``` + +#### Hex + +`0x`-prefixed hexadecimal string used for public keys and other hashes. + +```ts +type Hex = `0x${string}` & { + readonly [hashBrand]: never; +}; +``` + +#### MutationOptionsOverride + +TanStack Query `useMutation` options forwarded by AppKit's `use*Mutation` hooks via `parameters.mutation` — `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper and stripped from this shape. + +```ts +type MutationOptionsOverride = LooseOmit< + Query.MutationOptions, context>, + 'mutationFn' | 'mutationKey' | 'throwOnError' +>; +``` + +#### QueryOptionsOverride + +TanStack Query `useQuery` options forwarded by AppKit's `use*Query` hooks via `parameters.query` — `queryKey` and `queryFn` are managed by the wrapper and stripped from this shape. + +```ts +type QueryOptionsOverride = UnionLooseOmit, 'queryKey' | 'queryFn'>; +``` + +#### TokenAmount + +Decimal string carrying a token amount. Preserves precision and avoids floating-point rounding (e.g., `"1.5"` TON, or raw nano units depending on the API). + +```ts +type TokenAmount = string; +``` + +#### UserFriendlyAddress + +User-friendly TON wallet address as a base64url string (e.g., `"EQDtFp...4q2"`). + +```ts +type UserFriendlyAddress = string; +``` + +### Signing + +#### SignBinaryParameters + +Parameters accepted by [`signBinary`](#signbinary). + +| Field | Type | Description | +| --- | --- | --- | +| `bytes`\* | Base64String | Binary blob the user is asked to sign, encoded as Base64. | +| `network` | Network | Network to issue the sign request against. Defaults to AppKit's configured default network. When none is set, the wallet falls back to its current network. | + +#### SignBinaryReturnType + +Return type of [`signBinary`](#signbinary). + +```ts +type SignBinaryReturnType = SignDataResponse; +``` + +#### SignCellParameters + +Parameters accepted by [`signCell`](#signcell). + +| Field | Type | Description | +| --- | --- | --- | +| `cell`\* | Base64String | TON cell content encoded as Base64 (BoC). | +| `schema`\* | `string` | TL-B-style schema describing the cell layout so the wallet can render the payload to the user. | +| `network` | Network | Network to issue the sign request against. Defaults to AppKit's configured default network. When none is set, the wallet falls back to its current network. | + +#### SignCellReturnType + +Return type of [`signCell`](#signcell). + +```ts +type SignCellReturnType = SignDataResponse; +``` + +#### SignData + +Payload the user is asked to sign — discriminated union over `'text'`, `'binary'`, and `'cell'`. Nested under [`SignDataRequest`](#signdatarequest)'s `data`. + +```ts +type SignData = | { type: 'text'; value: SignDataText } + | { type: 'binary'; value: SignDataBinary } + | { type: 'cell'; value: SignDataCell }; +``` + +#### SignDataBinary + +Binary variant of [`SignData`](#signdata) — opaque byte content the user is asked to sign. + +| Field | Type | Description | +| --- | --- | --- | +| `content`\* | Base64String | Raw binary content encoded as Base64. | + +#### SignDataCell + +TON cell variant of [`SignData`](#signdata) — Base64-encoded cell payload paired with the schema needed to parse it. + +| Field | Type | Description | +| --- | --- | --- | +| `schema`\* | `string` | TL-B-style schema describing the cell layout so the wallet can render the payload to the user. | +| `content`\* | Base64String | Cell content encoded as Base64. | + +#### SignDataRequest + +Sign-data payload sent to [`WalletInterface`](#walletinterface)'s `signData` — discriminated by `data.type` (`'text'`, `'binary'`, or `'cell'`). + +| Field | Type | Description | +| --- | --- | --- | +| `network` | Network | Network to issue the sign request against. Defaults to the wallet's current network. | +| `from` | `string` | Sender address in raw format. Usually omitted, the wallet fills it in. | +| `data`\* | SignData | Payload the user is asked to sign. | + +#### SignDataResponse + +Wallet response to a [`SignDataRequest`](#signdatarequest) — carries the signature plus the canonicalized address, timestamp, and domain the wallet committed to. + +| Field | Type | Description | +| --- | --- | --- | +| `signature`\* | `string` | Base64-encoded signature. | +| `address`\* | `string` | Wallet address that signed, in user-friendly format. | +| `timestamp`\* | `number` | Unix timestamp the wallet stamped onto the signature. | +| `domain`\* | `string` | dApp domain the wallet bound the signature to. | +| `payload`\* | SignDataRequest | Original payload that was signed, echoed back for binding. | + +#### SignDataText + +Plain-text variant of [`SignData`](#signdata) — UTF-8 string the user is asked to sign. + +| Field | Type | Description | +| --- | --- | --- | +| `content`\* | `string` | UTF-8 text the user signs. | + +#### SignTextParameters + +Parameters accepted by [`signText`](#signtext). + +| Field | Type | Description | +| --- | --- | --- | +| `text`\* | `string` | UTF-8 text the user is asked to sign. | +| `network` | Network | Network to issue the sign request against. Defaults to AppKit's configured default network. When none is set, the wallet falls back to its current network. | + +#### SignTextReturnType + +Return type of [`signText`](#signtext). + +```ts +type SignTextReturnType = SignDataResponse; +``` + +### Staking + +#### BuildStakeTransactionOptions + +Options for [`buildStakeTransaction`](#buildstaketransaction) — extends [`StakeParams`](#stakeparams) with an optional provider override. + +| Field | Type | Description | +| --- | --- | --- | +| `quote`\* | StakingQuote | The staking quote based on which the transaction is built | +| `userAddress`\* | UserFriendlyAddress | Address of the user performing the staking | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerId` | `string` | Provider to stake/unstake through. Defaults to the registered default staking provider. | + +#### BuildStakeTransactionReturnType + +Return type of [`buildStakeTransaction`](#buildstaketransaction). + +```ts +type BuildStakeTransactionReturnType = Promise; +``` + +#### GetStakedBalanceOptions + +Options for [`getStakedBalance`](#getstakedbalance). + +| Field | Type | Description | +| --- | --- | --- | +| `userAddress`\* | UserFriendlyAddress | Owner whose staked balance should be read. | +| `network` | Network | Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `providerId` | `string` | Provider to query. Defaults to the registered default staking provider. | + +#### GetStakedBalanceReturnType + +Return type of [`getStakedBalance`](#getstakedbalance). + +```ts +type GetStakedBalanceReturnType = Promise; +``` + +#### GetStakingManagerReturnType + +Return type of [`getStakingManager`](#getstakingmanager). + +```ts +type GetStakingManagerReturnType = StakingManager; +``` + +#### GetStakingProviderInfoOptions + +Options for [`getStakingProviderInfo`](#getstakingproviderinfo). + +| Field | Type | Description | +| --- | --- | --- | +| `network` | Network | Network whose staking pool should be inspected. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `providerId` | `string` | Provider to query. Defaults to the registered default staking provider. | + +#### GetStakingProviderInfoReturnType + +Return type of [`getStakingProviderInfo`](#getstakingproviderinfo). + +```ts +type GetStakingProviderInfoReturnType = Promise; +``` + +#### GetStakingProviderMetadataOptions + +Options for [`getStakingProviderMetadata`](#getstakingprovidermetadata). + +| Field | Type | Description | +| --- | --- | --- | +| `network` | Network | Network whose provider metadata should be read. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | +| `providerId` | `string` | Provider to query. Defaults to the registered default staking provider. | + +#### GetStakingProviderMetadataReturnType + +Return type of [`getStakingProviderMetadata`](#getstakingprovidermetadata). + +```ts +type GetStakingProviderMetadataReturnType = StakingProviderMetadata; +``` + +#### GetStakingProviderOptions + +Options for [`getStakingProvider`](#getstakingprovider). + +| Field | Type | Description | +| --- | --- | --- | +| `id` | `string` | Provider ID to look up. When omitted, returns the registered default staking provider. | + +#### GetStakingProviderReturnType + +Return type of [`getStakingProvider`](#getstakingprovider). + +```ts +type GetStakingProviderReturnType = StakingProviderInterface; +``` + +#### GetStakingProvidersReturnType + +Return type of [`getStakingProviders`](#getstakingproviders). + +```ts +type GetStakingProvidersReturnType = StakingProviderInterface[]; +``` + +#### GetStakingQuoteOptions + +Options for [`getStakingQuote`](#getstakingquote) — extends [`StakingQuoteParams`](#stakingquoteparams) with an optional provider override. + +| Field | Type | Description | +| --- | --- | --- | +| `direction`\* | StakingQuoteDirection | Direction of the quote (stake or unstake) | +| `amount`\* | `string` | Amount of tokens to stake or unstake | +| `userAddress` | UserFriendlyAddress | Address of the user | +| `network` | Network | Network on which the staking will be executed | +| `unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | +| `isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerId` | `string` | Provider to quote against. Defaults to the registered default staking provider. | + +#### GetStakingQuoteReturnType + +Return type of [`getStakingQuote`](#getstakingquote). + +```ts +type GetStakingQuoteReturnType = Promise; +``` + +#### SetDefaultStakingProviderParameters + +Parameters accepted by [`setDefaultStakingProvider`](#setdefaultstakingprovider). + +| Field | Type | Description | +| --- | --- | --- | +| `providerId`\* | `string` | ID of the provider to make default — must already be registered. | + +#### SetDefaultStakingProviderReturnType + +Return type of [`setDefaultStakingProvider`](#setdefaultstakingprovider). + +```ts +type SetDefaultStakingProviderReturnType = void; +``` + +#### StakeParams + +Parameters for staking TON + +| Field | Type | Description | +| --- | --- | --- | +| `quote`\* | StakingQuote | The staking quote based on which the transaction is built | +| `userAddress`\* | UserFriendlyAddress | Address of the user performing the staking | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | + +#### StakingAPI + +Staking API interface exposed by StakingManager + +| Field | Type | Description | +| --- | --- | --- | +| `getQuote`\* | (params: StakingQuoteParams, providerId?: string) => Promise<StakingQuote> | Get a quote for staking or unstaking | +| `buildStakeTransaction`\* | (params: StakeParams, providerId?: string) => Promise<TransactionRequest> | Build a transaction for staking | +| `getStakedBalance`\* | (userAddress: UserFriendlyAddress, network?: Network, providerId?: string) => Promise<StakingBalance> | Get user's staked balance | +| `getStakingProviderInfo`\* | (network?: Network, providerId?: string) => Promise<StakingProviderInfo> | Get staking provider information | +| `getStakingProviderMetadata`\* | (network?: Network, providerId?: string) => StakingProviderMetadata | Get static metadata for a staking provider | +| `createFactoryContext`\* | () => ProviderFactoryContext | Build a fresh [`ProviderFactoryContext`](#providerfactorycontext) the manager hands to provider factories at registration time. | +| `registerProvider`\* | (provider: ProviderInput<StakingProviderInterface>) => void | Register a new provider. If a provider with the same id is already registered, it is replaced. | +| `removeProvider`\* | `(provider: StakingProviderInterface) => void` | Remove a previously registered provider. No-op if the provider was not registered. | +| `setDefaultProvider`\* | `(providerId: string) => void` | Set the default provider | +| `getProvider`\* | `(providerId?: string) => StakingProviderInterface` | Get a registered provider | +| `getProviders`\* | `() => Array` | Get all registered providers. The returned array keeps a stable reference until the provider list changes. | +| `hasProvider`\* | `(providerId: string) => boolean` | Check if a provider is registered | + +#### StakingBalance + +Staking balance information for a user + +| Field | Type | Description | +| --- | --- | --- | +| `rawStakedBalance`\* | TokenAmount | Amount currently staked, in raw smallest units of the stake token (e.g., nano-TON). | +| `stakedBalance`\* | `string` | Amount currently staked, formatted to the stake token's decimals as a human-readable decimal string (e.g., `"12.5"`). | +| `rawInstantUnstakeAvailable`\* | TokenAmount | Amount available for instant unstake, in raw smallest units of the stake token (e.g., nano-TON). | +| `instantUnstakeAvailable`\* | `string` | Amount available for instant unstake, formatted to the stake token's decimals as a human-readable decimal string (e.g., `"12.5"`). | +| `providerId`\* | `string` | Identifier of the staking provider | + +#### StakingProviderInfo + +Dynamic staking information for a provider + +| Field | Type | Description | +| --- | --- | --- | +| `apy`\* | `number` | Annual Percentage Yield in basis points (100 = 1%) | +| `rawInstantUnstakeAvailable` | TokenAmount | Amount available for instant unstake right now, in raw smallest units of the stake token (e.g., nano-TON). | +| `instantUnstakeAvailable` | `string` | Amount available for instant unstake right now, formatted to the stake token's decimals as a human-readable decimal string (e.g., `"12.5"`). | +| `exchangeRate` | `string` | Exchange rate between stakeToken and receiveToken (e.g. 1 TON = 0.95 tsTON). Undefined when there is no receiveToken (direct/custodial staking). | + +#### StakingProviderMetadata + +Static metadata for a staking provider + +| Field | Type | Description | +| --- | --- | --- | +| `name`\* | `string` | Human-readable provider name (e.g. "Tonstakers") | +| `supportedUnstakeModes`\* | UnstakeModes[] | Supported unstake modes for this provider | +| `supportsReversedQuote`\* | `boolean` | Whether provider supports reversed quote format (e.g., passing TON instead of tsTON for unstake) | +| `stakeToken`\* | StakingTokenInfo | Token that the user sends when staking (e.g. TON) | +| `receiveToken` | StakingTokenInfo | Token that the user receives when staking (e.g. tsTON for liquid staking). Absent for direct/custodial staking. | +| `contractAddress` | UserFriendlyAddress | Provider contract address (optional — custodial providers may not have one) | + +#### StakingProviderMetadataOverride + +Partial overrides applied on top of a provider's built-in [`StakingProviderMetadata`](#stakingprovidermetadata). Used in provider configuration (e.g. `TonStakersChainConfig.metadata`) when an integrator needs to tweak the display name, token info or supported modes for a specific chain. + +| Field | Type | Description | +| --- | --- | --- | +| `name` | `string` | Override the human-readable provider name surfaced in UIs. | +| `stakeToken` | StakingTokenInfo | Override the [`StakingTokenInfo`](#stakingtokeninfo) of the token the user sends when staking. | +| `receiveToken` | StakingTokenInfo | Override the [`StakingTokenInfo`](#stakingtokeninfo) of the token the user receives when staking (e.g. liquid-staking receipt). | +| `contractAddress` | UserFriendlyAddress | Override the provider contract address (user-friendly format). | +| `supportedUnstakeModes` | UnstakeModes[] | Override the list of supported unstake-timing modes. See [`UnstakeMode`](#unstakemode). | +| `supportsReversedQuote` | `boolean` | Override whether the provider supports reversed-amount quotes (e.g., specifying TON instead of tsTON on an unstake quote). | + +#### StakingQuote + +Staking quote response with pricing information + +| Field | Type | Description | +| --- | --- | --- | +| `direction`\* | StakingQuoteDirection | Direction of the quote (stake or unstake) | +| `rawAmountIn`\* | TokenAmount | Amount of tokens being provided | +| `rawAmountOut`\* | TokenAmount | Estimated amount of tokens to be received | +| `amountIn`\* | `string` | Formatted amount of tokens being provided | +| `amountOut`\* | `string` | Formatted estimated amount of tokens to be received | +| `network`\* | Network | Network on which the staking will be executed | +| `providerId`\* | `string` | Identifier of the staking provider | +| `unstakeMode` | UnstakeModes | Unstake-timing mode the quote was produced for. Only meaningful when `direction === 'unstake'` — for `'stake'` it is ignored. | +| `metadata` | `unknown` | Provider-specific metadata for the quote | + +#### StakingQuoteDirection + +Direction of the staking quote + +```ts +type StakingQuoteDirection = 'stake' | 'unstake'; +``` + +#### StakingQuoteParams + +Parameters for getting a staking quote + +| Field | Type | Description | +| --- | --- | --- | +| `direction`\* | StakingQuoteDirection | Direction of the quote (stake or unstake) | +| `amount`\* | `string` | Amount of tokens to stake or unstake | +| `userAddress` | UserFriendlyAddress | Address of the user | +| `network` | Network | Network on which the staking will be executed | +| `unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | +| `isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | + +#### StakingTokenInfo + +Display metadata for a staking-pool token — `ticker`, `decimals` and `address` (or `'ton'` for native TON). Carried on [`StakingProviderMetadata`](#stakingprovidermetadata)'s `stakeToken` and `receiveToken` so the UI can render the pool's input/output assets. + +| Field | Type | Description | +| --- | --- | --- | +| `ticker`\* | `string` | Ticker symbol (e.g., `"TON"`, `"tsTON"`). | +| `decimals`\* | `number` | Number of decimal places used to format raw amounts. | +| `address`\* | `string` | `'ton'` for native TON, otherwise the token contract address in user-friendly format. | + +#### TonStakersChainConfig + +Per-chain Tonstakers config — optional TonAPI key for APY reads and an optional staking-provider metadata override. + +| Field | Type | Description | +| --- | --- | --- | +| `tonApiToken` | `string` | TonAPI key used for APY reads. Optional — APY still works without it, but providing one is recommended when you already use TonAPI elsewhere. | +| `metadata` | StakingProviderMetadataOverride | Optional [`StakingProviderMetadataOverride`](#stakingprovidermetadataoverride) applied on top of the built-in Tonstakers metadata for this chain. | + +#### TonStakersProviderConfig + +Configuration accepted by [`createTonstakersProvider`](#createtonstakersprovider) — map of chain ID (e.g. `Network.mainnet().chainId`) to its per-chain [`TonStakersChainConfig`](#tonstakerschainconfig). + +```ts +type TonStakersProviderConfig = { + [chainId: string]: TonStakersChainConfig; +}; +``` + +#### UnstakeModes + +Union of [`UnstakeMode`](#unstakemode) values. Carried on [`StakingQuoteParams`](#stakingquoteparams)'s `unstakeMode` and on [`StakingProviderMetadata`](#stakingprovidermetadata)'s `supportedUnstakeModes` to discriminate `'INSTANT'` / `'WHEN_AVAILABLE'` / `'ROUND_END'` flows. + +```ts +type UnstakeModes = (typeof UnstakeMode)[keyof typeof UnstakeMode]; +``` + +#### WatchStakingProvidersParameters + +Parameters accepted by [`watchStakingProviders`](#watchstakingproviders). + +| Field | Type | Description | +| --- | --- | --- | +| `onChange`\* | `() => void` | Callback fired whenever a staking provider is registered or the default staking provider changes. | + +#### WatchStakingProvidersReturnType + +Return type of [`watchStakingProviders`](#watchstakingproviders) — call to stop receiving updates. + +```ts +type WatchStakingProvidersReturnType = () => void; +``` + +### Swap + +#### BuildSwapTransactionOptions + +Options for [`buildSwapTransaction`](#buildswaptransaction) — same shape as [`SwapParams`](#swapparams). + +```ts +type BuildSwapTransactionOptions = SwapParams; +``` + +#### BuildSwapTransactionReturnType + +Return type of [`buildSwapTransaction`](#buildswaptransaction). + +```ts +type BuildSwapTransactionReturnType = Promise; +``` + +#### DeDustProviderOptions + +DeDust-specific options forwarded through `providerOptions` on [`SwapQuoteParams`](#swapquoteparams) / [`SwapParams`](#swapparams). + +| Field | Type | Description | +| --- | --- | --- | +| `protocols` | `string[]` | Protocols to use for routing. Available values: `'dedust'`, `'dedust_v3'`, `'dedust_v3_memepad'`, `'stonfi_v1'`, `'stonfi_v2'`, `'tonco'`, `'memeslab'`, `'tonfun'`. Defaults to all protocols when omitted. | +| `excludeProtocols` | `string[]` | Protocols to exclude from routing | +| `onlyVerifiedPools` | `boolean` | Only use verified pools | +| `maxSplits` | `number` | Maximum number of route splits | +| `maxLength` | `number` | Maximum route length (hops) | +| `excludeVolatilePools` | `boolean` | Exclude volatile pools | +| `referralAddress` | `string` | The address of the referrer | +| `referralFeeBps` | `number` | Referral fee in basis points (max 100 = 1%) | + +#### DeDustQuoteMetadata + +Provider-specific metadata returned on a [`SwapQuote`](#swapquote)'s `metadata` from DeDust — carries the resolved route, fees and `swapData` payload that [`buildSwapTransaction`](#buildswaptransaction) needs. + +| Field | Type | Description | +| --- | --- | --- | +| `quoteResponse`\* | `DeDustQuoteResponse` | Raw quote response from API | +| `slippageBps`\* | `number` | Slippage used for the quote in basis points | + +#### DeDustReferralOptions + +Optional referral metadata attached to DeDust swaps so the provider can attribute them. + +| Field | Type | Description | +| --- | --- | --- | +| `referralAddress` | `string` | The address of the referrer | +| `referralFeeBps` | `number` | Referral fee in basis points (max 100 = 1%) | + +#### DeDustSwapProviderConfig + +Configuration accepted by [`createDeDustProvider`](#creatededustprovider). + +| Field | Type | Description | +| --- | --- | --- | +| `providerId` | `string` | Custom provider ID (defaults to 'dedust') | +| `defaultSlippageBps` | `number` | Default slippage tolerance in basis points (1 bp = 0.01%) | +| `apiUrl` | `string` | API base URL | +| `onlyVerifiedPools` | `boolean` | Only use verified pools | +| `maxSplits` | `number` | Maximum number of route splits | +| `maxLength` | `number` | Maximum route length (hops) | +| `minPoolUsdTvl` | `string` | Minimum pool TVL in USD | +| `metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider | +| `referralAddress` | `string` | The address of the referrer | +| `referralFeeBps` | `number` | Referral fee in basis points (max 100 = 1%) | + +#### GetSwapManagerReturnType + +Return type of [`getSwapManager`](#getswapmanager). + +```ts +type GetSwapManagerReturnType = SwapManager; +``` + +#### GetSwapProviderOptions + +Options for [`getSwapProvider`](#getswapprovider). + +| Field | Type | Description | +| --- | --- | --- | +| `id` | `string` | Provider ID to look up. When omitted, returns the registered default swap provider. | + +#### GetSwapProviderReturnType + +Return type of [`getSwapProvider`](#getswapprovider). + +```ts +type GetSwapProviderReturnType = SwapProviderInterface; +``` + +#### GetSwapProvidersReturnType + +Return type of [`getSwapProviders`](#getswapproviders). + +```ts +type GetSwapProvidersReturnType = SwapProviderInterface[]; +``` + +#### GetSwapQuoteOptions + +Options for [`getSwapQuote`](#getswapquote) — extends [`SwapQuoteParams`](#swapquoteparams) with an optional provider override. + +| Field | Type | Description | +| --- | --- | --- | +| `amount`\* | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | +| `from`\* | SwapToken | Token to swap from | +| `to`\* | SwapToken | Token to swap to | +| `network`\* | Network | Network on which the swap will be executed | +| `slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | +| `maxOutgoingMessages` | `number` | Maximum number of outgoing messages | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | +| `providerId` | `string` | Provider to quote against. Defaults to the registered default swap provider. | + +#### GetSwapQuoteReturnType + +Return type of [`getSwapQuote`](#getswapquote). + +```ts +type GetSwapQuoteReturnType = Promise; +``` + +#### OmnistonProviderOptions + +Omniston-specific options forwarded through `providerOptions` on [`SwapQuoteParams`](#swapquoteparams) / [`SwapParams`](#swapparams). + +| Field | Type | Description | +| --- | --- | --- | +| `settlementMethods` | `SettlementMethodValue[]` | Settlement methods to use for the swap | +| `referrerAddress` | `string` | The address of the referrer | +| `referrerFeeBps` | `number` | Referrer fee in basis points (1 bp = 0.01%) | +| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed | + +#### OmnistonQuoteMetadata + +Provider-specific metadata returned on a [`SwapQuote`](#swapquote)'s `metadata` from Omniston — carries the resolved route and signed quote payload that [`buildSwapTransaction`](#buildswaptransaction) needs. + +| Field | Type | Description | +| --- | --- | --- | +| `omnistonQuote`\* | `Quote` | The actual Omniston quote object | + +#### OmnistonReferrerOptions + +Optional referrer metadata attached to Omniston swaps so the provider can attribute them. + +| Field | Type | Description | +| --- | --- | --- | +| `referrerAddress` | `string` | The address of the referrer | +| `referrerFeeBps` | `number` | Referrer fee in basis points (1 bp = 0.01%) | +| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed | + +#### OmnistonSwapProviderConfig + +Configuration accepted by [`createOmnistonProvider`](#createomnistonprovider). + +| Field | Type | Description | +| --- | --- | --- | +| `apiUrl` | `string` | Optional URL for the Omniston API | +| `defaultSlippageBps` | `number` | Default slippage tolerance in basis points (1 bp = 0.01%) | +| `quoteTimeoutMs` | `number` | Timeout for quote requests in milliseconds | +| `providerId` | `string` | Identifier for the provider | +| `metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider | +| `referrerAddress` | `string` | The address of the referrer | +| `referrerFeeBps` | `number` | Referrer fee in basis points (1 bp = 0.01%) | +| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed | + +#### SetDefaultSwapProviderParameters + +Parameters accepted by [`setDefaultSwapProvider`](#setdefaultswapprovider). + +| Field | Type | Description | +| --- | --- | --- | +| `providerId`\* | `string` | ID of the provider to make default — must already be registered. | + +#### SetDefaultSwapProviderReturnType + +Return type of [`setDefaultSwapProvider`](#setdefaultswapprovider). + +```ts +type SetDefaultSwapProviderReturnType = void; +``` + +#### SwapAPI + +API surface exposed by [`SwapManager`](#swapmanager) — quote and build-transaction calls (plus the provider-management methods inherited from [`DefiManagerAPI`](#defimanagerapi)). Mostly relevant when authoring a swap manager replacement. + +| Field | Type | Description | +| --- | --- | --- | +| `getQuote`\* | (params: SwapQuoteParams, providerId?: string) => Promise<SwapQuote> | Get a quote for swapping tokens | +| `buildSwapTransaction`\* | (params: SwapParams) => Promise<TransactionRequest> | Build a transaction for a swap. Provider is taken from `params.quote.providerId`, or the manager default. | +| `createFactoryContext`\* | () => ProviderFactoryContext | Build a fresh [`ProviderFactoryContext`](#providerfactorycontext) the manager hands to provider factories at registration time. | +| `registerProvider`\* | (provider: ProviderInput<SwapProviderInterface<unknown, unknown>>) => void | Register a new provider. If a provider with the same id is already registered, it is replaced. | +| `removeProvider`\* | `(provider: SwapProviderInterface) => void` | Remove a previously registered provider. No-op if the provider was not registered. | +| `setDefaultProvider`\* | `(providerId: string) => void` | Set the default provider | +| `getProvider`\* | `(providerId?: string) => SwapProviderInterface` | Get a registered provider | +| `getProviders`\* | `() => Array>` | Get all registered providers. The returned array keeps a stable reference until the provider list changes. | +| `hasProvider`\* | `(providerId: string) => boolean` | Check if a provider is registered | + +#### SwapParams + +Parameters consumed by [`buildSwapTransaction`](#buildswaptransaction) — the previously obtained [`SwapQuote`](#swapquote) plus optional provider-specific options (`TProviderOptions`). + +| Field | Type | Description | +| --- | --- | --- | +| `quote`\* | SwapQuote | The swap quote based on which the transaction is built | +| `userAddress`\* | UserFriendlyAddress | Address of the user performing the swap | +| `destinationAddress` | UserFriendlyAddress | Address to receive the swapped tokens (defaults to userAddress) | +| `slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | +| `deadline` | `number` | Unix timestamp (in seconds) after which the swap transaction must not be executed. | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | + +#### SwapQuote + +Quote returned by [`getSwapQuote`](#getswapquote) — source/target tokens, expected amounts, rate, slippage, fees and the provider-specific `metadata` that [`buildSwapTransaction`](#buildswaptransaction) needs to construct the transaction. + +| Field | Type | Description | +| --- | --- | --- | +| `fromToken`\* | SwapToken | Token being sold | +| `toToken`\* | SwapToken | Token being bought | +| `rawFromAmount`\* | TokenAmount | Amount of tokens to sell | +| `rawToAmount`\* | TokenAmount | Amount of tokens to buy | +| `fromAmount`\* | `string` | Amount of tokens to sell | +| `toAmount`\* | `string` | Amount of tokens to buy | +| `rawMinReceived`\* | TokenAmount | Minimum amount of tokens to receive (after slippage) | +| `minReceived`\* | `string` | Minimum amount of tokens to receive (after slippage) | +| `network`\* | Network | Network on which the swap will be executed | +| `priceImpact` | `number` | Price impact of the swap in basis points (100 = 1%) | +| `providerId`\* | `string` | Identifier of the swap provider | +| `expiresAt` | `number` | Unix timestamp in seconds when the quote expires | +| `metadata` | `unknown` | Provider-specific metadata for the quote | + +#### SwapQuoteParams + +Parameters consumed by [`getSwapQuote`](#getswapquote) — source/target tokens and an amount that is interpreted as either the spend side or the receive side (`isReverseSwap` flag), plus optional slippage and provider-specific options. + +| Field | Type | Description | +| --- | --- | --- | +| `amount`\* | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | +| `from`\* | SwapToken | Token to swap from | +| `to`\* | SwapToken | Token to swap to | +| `network`\* | Network | Network on which the swap will be executed | +| `slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | +| `maxOutgoingMessages` | `number` | Maximum number of outgoing messages | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | + +#### SwapToken + +Token descriptor passed to [`getSwapQuote`](#getswapquote) via [`SwapQuoteParams`](#swapquoteparams)'s `from` and `to` fields (and surfaced on the resulting [`SwapQuote`](#swapquote)) — address, decimals plus optional symbol/name/image used by swap-input UIs. + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | `string` | Token contract address. `'ton'` is used for native TON on the TON chain. | +| `decimals`\* | `number` | Number of decimal places used to format raw amounts. | +| `name` | `string` | Display name (e.g., `"Tether USD"`). | +| `symbol` | `string` | Ticker symbol (e.g., `"USDT"`). | +| `image` | `string` | URL of the token's image. | +| `chainId` | `string` | Chain id in CAIP-2 format when the token lives outside TON. | + +#### WatchSwapProvidersParameters + +Parameters accepted by [`watchSwapProviders`](#watchswapproviders). + +| Field | Type | Description | +| --- | --- | --- | +| `onChange`\* | `() => void` | Callback fired whenever a swap provider is registered or the default swap provider changes. | + +#### WatchSwapProvidersReturnType + +Return type of [`watchSwapProviders`](#watchswapproviders) — call to stop receiving updates. + +```ts +type WatchSwapProvidersReturnType = () => void; +``` + +### Transactions + +#### CreateTransferTonTransactionParameters + +Parameters accepted by [`createTransferTonTransaction`](#createtransfertontransaction) and [`transferTon`](#transferton). + +| Field | Type | Description | +| --- | --- | --- | +| `recipientAddress`\* | UserFriendlyAddress | Recipient address. | +| `amount`\* | `string` | Amount in TON as a human-readable decimal string (e.g., `"1.5"`). Converted to nano-TON internally. | +| `comment` | `string` | Human-readable text comment. Converted to a Base64 payload when no `payload` is supplied. | +| `payload` | Base64String | Raw Base64 message payload — wins over `comment` when both are set. | +| `stateInit` | Base64String | Initial state for deploying a new contract, encoded as Base64. | + +#### CreateTransferTonTransactionReturnType + +Return type of [`createTransferTonTransaction`](#createtransfertontransaction). + +```ts +type CreateTransferTonTransactionReturnType = TransactionRequest; +``` + +#### GetTransactionStatusParameters + +Parameters accepted by [`getTransactionStatus`](#gettransactionstatus) — must carry exactly one of `boc` or `normalizedHash`, plus an optional network override. + +```ts +type GetTransactionStatusParameters = { + /** Network to check the transaction on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ + network?: Network; +} & ( + | { + /** Base64-encoded BoC of the sent transaction (returned by {@link sendTransaction}). */ + boc: string; + normalizedHash?: never; + } + | { + boc?: never; + /** Hex-encoded normalized hash of the external-in message (returned by {@link sendTransaction} as `normalizedHash`). */ + normalizedHash: string; + } +); +``` + +#### GetTransactionStatusReturnType + +Return type of [`getTransactionStatus`](#gettransactionstatus). + +```ts +type GetTransactionStatusReturnType = TransactionStatusResponse; +``` + +#### SendTransactionParameters + +Parameters accepted by [`sendTransaction`](#sendtransaction) — same shape as [`TransactionRequest`](#transactionrequest). + +```ts +type SendTransactionParameters = TransactionRequest; +``` + +#### SendTransactionResponse + +Wallet response carrying the BoC (bag of cells) of the external message that was signed and broadcast — used to track or hash the resulting transaction. + +| Field | Type | Description | +| --- | --- | --- | +| `boc`\* | Base64String | BoC of the sent transaction | +| `normalizedBoc`\* | Base64String | Normalized BoC of the external-in message | +| `normalizedHash`\* | Hex | Hash of the normalized external-in message | + +#### SendTransactionReturnType + +Return type of [`sendTransaction`](#sendtransaction). + +```ts +type SendTransactionReturnType = SendTransactionResponse; +``` + +#### Transaction + +Single transaction record carried inside [`TransactionsUpdate`](#transactionsupdate)'s `transactions` — account, lt/hash, in/out messages and emulation result. + +| Field | Type | Description | +| --- | --- | --- | +| `account`\* | UserFriendlyAddress | Account of the transaction | +| `accountStateBefore` | `AccountState` | The state of the account before the transaction was executed | +| `accountStateAfter` | `AccountState` | The state of the account after the transaction has been applied | +| `description` | `TransactionDescription` | The detailed breakdown of the transaction execution | +| `hash`\* | Hex | Hash of the transaction | +| `logicalTime`\* | `LogicalTime` | The logical time of the transaction | +| `now`\* | `number` | Unix timestamp of the transaction | +| `mcBlockSeqno`\* | `number` | Masterchain block sequence number | +| `traceExternalHash`\* | Hex | External hash of the trace | +| `traceId` | `string` | ID of the trace | +| `previousTransactionHash` | `string` | The hash of the previous transaction | +| `previousTransactionLogicalTime` | `LogicalTime` | The logical time of the previous transaction | +| `origStatus` | `AccountStatus` | Original status of the transaction | +| `endStatus` | `AccountStatus` | End status of the transaction | +| `totalFees` | TokenAmount | Total fees of the transaction | +| `totalFeesExtraCurrencies` | ExtraCurrencies | Extra currencies in the total fees | +| `blockRef` | `TransactionBlockRef` | The reference to the block in which the transaction was included | +| `inMessage` | `TransactionMessage` | The incoming message associated with the transaction | +| `outMessages`\* | `TransactionMessage[]` | The list of outgoing messages produced by the transaction | +| `isEmulated`\* | `boolean` | Emulated state of the transaction | + +#### TransactionRequest + +Transaction payload passed to [`WalletInterface`](#walletinterface)'s `sendTransaction` — one or more messages, optional network override and `validUntil` deadline. + +| Field | Type | Description | +| --- | --- | --- | +| `messages`\* | TransactionRequestMessage[] | Messages to include in the transaction. | +| `network` | Network | Network to execute the transaction on. | +| `validUntil` | `number` | Unix timestamp (seconds) after which the transaction becomes invalid. | +| `fromAddress` | `string` | Sender wallet address — accepts either raw or user-friendly format. | + +#### TransactionRequestMessage + +Individual message inside a [`TransactionRequest`](#transactionrequest) — recipient, amount, optional payload and contract `stateInit`. + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | `string` | Recipient wallet address — accepts either raw or user-friendly format. | +| `amount`\* | TokenAmount | Amount to transfer, in nano-TON (1 TON = 10⁹ nano-TON). | +| `extraCurrency` | ExtraCurrencies | Additional currencies to include in the transfer. | +| `stateInit` | `string` | Initial state for deploying a new contract, encoded as Base64. | +| `payload` | `string` | Message payload, encoded as Base64. | + +#### TransactionsUpdate + +Update payload delivered to [`watchTransactions`](#watchtransactions) / [`watchTransactionsByAddress`](#watchtransactionsbyaddress) subscribers when transactions land for the watched address. + +| Field | Type | Description | +| --- | --- | --- | +| `type`\* | `'transactions'` | The update type field | +| `address`\* | UserFriendlyAddress | The account address | +| `transactions`\* | Transaction[] | The array of transactions | +| `traceHash`\* | Hex | The hash of the trace | +| `addressBook` | AddressBook | Address book from streaming v2 notification | +| `metadata` | `TransactionAddressMetadata` | Metadata from streaming v2 notification | +| `status`\* | StreamingUpdateStatus | The finality of the update | + +#### TransferTonParameters + +Parameters accepted by [`transferTon`](#transferton) — same shape as [`CreateTransferTonTransactionParameters`](#createtransfertontransactionparameters). + +```ts +type TransferTonParameters = CreateTransferTonTransactionParameters; +``` + +#### TransferTonReturnType + +Return type of [`transferTon`](#transferton). + +```ts +type TransferTonReturnType = SendTransactionResponse; +``` + +#### WatchTransactionsByAddressOptions + +Options for [`watchTransactionsByAddress`](#watchtransactionsbyaddress). + +| Field | Type | Description | +| --- | --- | --- | +| `address`\* | UserFriendlyAddress \| Address | Address to watch — pass a [`UserFriendlyAddress`](#userfriendlyaddress) string or an `Address` instance from `@ton/core`. | +| `onChange`\* | (update: TransactionsUpdate) => void | Callback fired on every transactions update from the streaming provider. | +| `network` | Network | Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. | + +#### WatchTransactionsByAddressReturnType + +Return type of [`watchTransactionsByAddress`](#watchtransactionsbyaddress) — call to stop receiving updates. + +```ts +type WatchTransactionsByAddressReturnType = () => void; +``` + +#### WatchTransactionsOptions + +Options for [`watchTransactions`](#watchtransactions). + +| Field | Type | Description | +| --- | --- | --- | +| `onChange`\* | (update: TransactionsUpdate) => void | Callback fired on every transactions update from the streaming provider. | +| `network` | Network | Network to watch on. Defaults to the selected wallet's network. | + +#### WatchTransactionsReturnType + +Return type of [`watchTransactions`](#watchtransactions) — call to stop receiving updates. + +```ts +type WatchTransactionsReturnType = () => void; +``` + +### Wallets + +#### GetConnectedWalletsReturnType + +Return type of [`getConnectedWallets`](#getconnectedwallets) — read-only view of the connected-wallets array. + +```ts +type GetConnectedWalletsReturnType = readonly WalletInterface[]; +``` + +#### GetSelectedWalletReturnType + +Return type of [`getSelectedWallet`](#getselectedwallet) — `null` when no wallet is currently selected. + +```ts +type GetSelectedWalletReturnType = WalletInterface | null; +``` + +#### SetSelectedWalletIdParameters + +Parameters accepted by [`setSelectedWalletId`](#setselectedwalletid). + +| Field | Type | Description | +| --- | --- | --- | +| `walletId`\* | `string \| null` | Wallet ID (as returned by [`WalletInterface`](#walletinterface)'s `getWalletId()`) to select. Pass `null` to clear the selection. | + +#### SetSelectedWalletIdReturnType + +Return type of [`setSelectedWalletId`](#setselectedwalletid). + +```ts +type SetSelectedWalletIdReturnType = void; +``` + +#### TonConnectWalletAdapterConfig + +Configuration accepted by [`TonConnectWalletAdapter`](#tonconnectwalletadapter) when wrapping a TonConnect wallet for AppKit. + +| Field | Type | Description | +| --- | --- | --- | +| `connectorId`\* | `string` | ID of the connector that produced this wallet — surfaced as `WalletInterface.connectorId`. | +| `tonConnectWallet`\* | `TonConnectWallet` | Underlying TonConnect wallet object. | +| `tonConnectUI`\* | `TonConnectUI` | TonConnect UI instance used to drive `sendTransaction` and `signData` calls. | + +#### WalletInterface + +Wallet contract surfaced by every [`Connector`](#connector) — covers identity (address, public key, network) and signing operations. Reads (balance, jettons, NFTs) go through AppKit actions instead. + +| Field | Type | Description | +| --- | --- | --- | +| `connectorId`\* | `string` | ID of the [`Connector`](#connector) that produced this wallet. | +| `getAddress`\* | () => UserFriendlyAddress | Wallet address as a user-friendly base64url string. | +| `getPublicKey`\* | () => Hex | Wallet public key as a `0x`-prefixed hex string. | +| `getNetwork`\* | () => Network | Network the wallet is currently connected to. | +| `getWalletId`\* | `() => string` | Stable identifier combining address and network — unique across AppKit's connected wallets. | +| `sendTransaction`\* | (request: TransactionRequest) => Promise<SendTransactionResponse> | Send a transaction — the wallet signs and broadcasts it. | +| `signData`\* | (payload: SignDataRequest) => Promise<SignDataResponse> | Sign arbitrary data — text, binary or TON cell — through the wallet's sign-data flow. | + +#### WatchConnectedWalletsParameters + +Parameters accepted by [`watchConnectedWallets`](#watchconnectedwallets). + +| Field | Type | Description | +| --- | --- | --- | +| `onChange`\* | (wallets: WalletInterface[]) => void | Callback fired whenever the list of connected wallets changes — receives the latest snapshot. | + +#### WatchConnectedWalletsReturnType + +Return type of [`watchConnectedWallets`](#watchconnectedwallets) — call to stop receiving updates. + +```ts +type WatchConnectedWalletsReturnType = () => void; +``` + +#### WatchSelectedWalletParameters + +Parameters accepted by [`watchSelectedWallet`](#watchselectedwallet). + +| Field | Type | Description | +| --- | --- | --- | +| `onChange`\* | (wallet: WalletInterface \| null) => void | Callback fired whenever the selected wallet changes — receives the new wallet, or `null` when the selection was cleared. | + +#### WatchSelectedWalletReturnType + +Return type of [`watchSelectedWallet`](#watchselectedwallet) — call to stop receiving updates. + +```ts +type WatchSelectedWalletReturnType = () => void; +``` + +## Constants + +### Connectors + +#### CONNECTOR_EVENTS + +Event names AppKit emits for connector-list and connector-wallet changes. Payloads are [`ConnectorAddedPayload`](#connectoraddedpayload), [`ConnectorRemovedPayload`](#connectorremovedpayload) and [`ConnectorWalletsUpdatedPayload`](#connectorwalletsupdatedpayload). + +```ts +const CONNECTOR_EVENTS = { + /** A connector was registered via {@link addConnector} (or AppKit's constructor). */ + ADDED: 'connector:added', + /** A connector was unregistered — typically by calling the unregister function returned from {@link addConnector}, or as part of the connector's own teardown. */ + REMOVED: 'connector:removed', + /** A connector's connected-wallets list changed (connect, disconnect, or account switch inside the wallet). */ + WALLETS_UPDATED: 'connector:wallets-updated', +} as const; +``` + +#### TONCONNECT_DEFAULT_CONNECTOR_ID + +Default id assigned to the TonConnect connector when none is supplied to [`createTonConnectConnector`](#createtonconnectconnector). Pass this to [`connect`](#connect) / [`disconnect`](#disconnect) to drive the TonConnect flow without hard-coding the literal. + +```ts +const TONCONNECT_DEFAULT_CONNECTOR_ID = 'tonconnect'; +``` + +### Crypto Onramp + +#### CryptoOnrampErrorCode + +Discriminator carried on every [`CryptoOnrampError`](#cryptoonramperror)'s `code` — covers provider/quote/deposit failures and refund-address validation. + +| Field | Type | Description | +| --- | --- | --- | +| `ProviderError`\* | `"PROVIDER_ERROR"` | Provider's upstream API rejected the call (unexpected response, auth failure, internal error). | +| `QuoteFailed`\* | `"QUOTE_FAILED"` | Provider could not produce a quote for the supplied parameters. | +| `DepositFailed`\* | `"DEPOSIT_FAILED"` | Provider could not create a deposit for the previously obtained quote. | +| `RefundAddressRequired`\* | `"REFUND_ADDRESS_REQUIRED"` | Provider requires a refund address that the caller did not supply. | +| `InvalidRefundAddress`\* | `"INVALID_REFUND_ADDRESS"` | Supplied refund address is not valid for the source chain. | +| `ReversedAmountNotSupported`\* | `"REVERSED_AMOUNT_NOT_SUPPORTED"` | Provider does not support specifying the amount on the target side of the swap. | +| `InvalidParams`\* | `"INVALID_PARAMS"` | Caller passed parameters that fail provider-level validation. | + +### DeFi + +#### DefiErrorCode + +Discriminator carried on [`DefiError`](#defierror)'s `code` for codes shared by every DeFi domain — provider lookup, default-provider state, and shared transport/validation failures. Subclass codes ([`SwapErrorCode`](#swaperrorcode), [`StakingErrorCode`](#stakingerrorcode), [`CryptoOnrampErrorCode`](#cryptoonramperrorcode)) cover domain-specific failures. + +| Field | Type | Description | +| --- | --- | --- | +| `ProviderNotFound`\* | `"PROVIDER_NOT_FOUND"` | Provider with the requested id is not registered with the manager. | +| `NoDefaultProvider`\* | `"NO_DEFAULT_PROVIDER"` | No default provider is configured and the caller did not specify one. | +| `NetworkError`\* | `"NETWORK_ERROR"` | Provider rejected the request because of an upstream/network failure. | +| `UnsupportedNetwork`\* | `"UNSUPPORTED_NETWORK"` | Provider does not support the network selected for the operation. | +| `InvalidParams`\* | `"INVALID_PARAMS"` | Caller passed parameters that fail provider-level validation. | +| `InvalidProvider`\* | `"INVALID_PROVIDER"` | Provider failed its own internal validation and cannot be used. | + +### Networks + +#### NETWORKS_EVENTS + +Event names AppKit emits on network changes. `DEFAULT_CHANGED` carries a [`DefaultNetworkChangedPayload`](#defaultnetworkchangedpayload). + +```ts +const NETWORKS_EVENTS = { + UPDATED: 'networks:updated', + DEFAULT_CHANGED: 'networks:default-changed', +} as const; +``` + +### Staking + +#### StakingErrorCode + +Discriminator carried on every [`StakingError`](#stakingerror)'s `code` — `'INVALID_PARAMS'` (the request was malformed) or `'UNSUPPORTED_OPERATION'` (the provider doesn't support this call). + +| Field | Type | Description | +| --- | --- | --- | +| `InvalidParams`\* | `"INVALID_PARAMS"` | Caller passed parameters that fail provider-level validation. | +| `UnsupportedOperation`\* | `"UNSUPPORTED_OPERATION"` | Provider doesn't support the requested operation (e.g., reversed quote on a unidirectional pool). | + +#### UnstakeMode + +Allowed unstake-timing flavours referenced by [`UnstakeModes`](#unstakemodes) and [`StakingProviderMetadata`](#stakingprovidermetadata)'s `supportedUnstakeModes` — `'INSTANT'` (immediate withdrawal when the pool has liquidity, otherwise the funds are returned), `'WHEN_AVAILABLE'` (paid out as soon as liquidity is available — instantly or at round end), `'ROUND_END'` (paid out at the end of the staking round, typically for the best rate). + +```ts +const UnstakeMode = { readonly INSTANT: "INSTANT"; readonly WHEN_AVAILABLE: "WHEN_AVAILABLE"; readonly ROUND_END: "ROUND_END"; }; +``` + +### Swap + +#### SwapErrorCode + +Discriminator carried on every [`SwapError`](#swaperror)'s `code` — covers quote / liquidity / transaction-build failures plus the shared `NETWORK_ERROR` for upstream-API faults. + +| Field | Type | Description | +| --- | --- | --- | +| `InvalidQuote`\* | `"INVALID_QUOTE"` | Provider returned malformed or missing quote data. | +| `InsufficientLiquidity`\* | `"INSUFFICIENT_LIQUIDITY"` | No route or pool has enough liquidity to satisfy the requested swap. | +| `QuoteExpired`\* | `"QUOTE_EXPIRED"` | Quote payload is too old to use. Fetch a new one before building the transaction. | +| `BuildTxFailed`\* | `"BUILD_TX_FAILED"` | Provider failed to produce a swap transaction from the supplied quote. | +| `NetworkError`\* | `"NETWORK_ERROR"` | Provider rejected the request because of an upstream/network failure. | + +### Wallets + +#### WALLETS_EVENTS + +Event names AppKit emits when the available wallet list (`UPDATED`) or the active wallet (`SELECTION_CHANGED`) changes. + +```ts +const WALLETS_EVENTS = { + UPDATED: 'wallets:updated', + SELECTION_CHANGED: 'wallets:selection-changed', +} as const; +``` diff --git a/packages/appkit/docs/staking.md b/packages/appkit/docs/staking.md index eff1434fa..e8d1d1bdf 100644 --- a/packages/appkit/docs/staking.md +++ b/packages/appkit/docs/staking.md @@ -1,7 +1,7 @@ # Staking diff --git a/packages/appkit/docs/swap.md b/packages/appkit/docs/swap.md index 1847973b2..697b2189c 100644 --- a/packages/appkit/docs/swap.md +++ b/packages/appkit/docs/swap.md @@ -1,7 +1,7 @@ # Swap diff --git a/packages/appkit/src/actions/balances/get-balance-by-address.ts b/packages/appkit/src/actions/balances/get-balance-by-address.ts index d4833395c..407dce98e 100644 --- a/packages/appkit/src/actions/balances/get-balance-by-address.ts +++ b/packages/appkit/src/actions/balances/get-balance-by-address.ts @@ -7,19 +7,50 @@ */ import { Address } from '@ton/core'; -import type { TokenAmount, Network } from '@ton/walletkit'; -import { formatUnits } from '@ton/walletkit'; import type { AppKit } from '../../core/app-kit'; +import type { TokenAmount, UserFriendlyAddress } from '../../types/primitives'; +import type { Network } from '../../types/network'; +import { formatUnits } from '../../utils'; import { resolveNetwork } from '../../utils/network/resolve-network'; +/** + * Options for {@link getBalanceByAddress}. + * + * @public + * @category Type + * @section Balances + */ export interface GetBalanceByAddressOptions { - address: string | Address; + /** Wallet address — pass a {@link UserFriendlyAddress} string or an `Address` instance from `@ton/core`. */ + address: UserFriendlyAddress | Address; + /** Network to read the balance from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; } +/** + * Return type of {@link getBalanceByAddress}. + * + * @public + * @category Type + * @section Balances + */ export type GetBalanceByAddressReturnType = TokenAmount; +/** + * Read the Toncoin balance of an arbitrary address — useful for wallets that aren't selected in AppKit (use {@link getBalance} for the selected wallet). + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetBalanceByAddressOptions} Target address and optional network. + * @returns Balance in TON as a human-readable decimal string. + * + * @sample docs/examples/src/appkit/actions/balances#GET_BALANCE_BY_ADDRESS + * @expand options + * + * @public + * @category Action + * @section Balances + */ export const getBalanceByAddress = async ( appKit: AppKit, options: GetBalanceByAddressOptions, diff --git a/packages/appkit/src/actions/balances/get-balance.ts b/packages/appkit/src/actions/balances/get-balance.ts index 3fd874984..d684e6937 100644 --- a/packages/appkit/src/actions/balances/get-balance.ts +++ b/packages/appkit/src/actions/balances/get-balance.ts @@ -6,19 +6,47 @@ * */ -import type { TokenAmount } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { TokenAmount } from '../../types/primitives'; +import type { Network } from '../../types/network'; import { getSelectedWallet } from '../wallets/get-selected-wallet'; import { getBalanceByAddress } from './get-balance-by-address'; -import type { Network } from '../../types/network'; +/** + * Options for {@link getBalance}. + * + * @public + * @category Type + * @section Balances + */ export interface GetBalanceOptions { + /** Network to read the balance from. Defaults to the selected wallet's network. */ network?: Network; } +/** + * Return type of {@link getBalance}. + * + * @public + * @category Type + * @section Balances + */ export type GetBalanceReturnType = TokenAmount | null; +/** + * Read the Toncoin balance of the currently selected wallet, returning `null` when no wallet is selected (use {@link getBalanceByAddress} for an arbitrary address). + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetBalanceOptions} Optional network override. + * @returns Balance in TON as a human-readable decimal string, or `null` when no wallet is selected. + * + * @sample docs/examples/src/appkit/actions/balances#GET_BALANCE + * @expand options + * + * @public + * @category Action + * @section Balances + */ export const getBalance = async (appKit: AppKit, options: GetBalanceOptions = {}): Promise => { const selectedWallet = getSelectedWallet(appKit); diff --git a/packages/appkit/src/actions/balances/watch-balance-by-address.ts b/packages/appkit/src/actions/balances/watch-balance-by-address.ts index 6116e7fc9..e521020ee 100644 --- a/packages/appkit/src/actions/balances/watch-balance-by-address.ts +++ b/packages/appkit/src/actions/balances/watch-balance-by-address.ts @@ -7,21 +7,51 @@ */ import { Address } from '@ton/core'; -import type { BalanceUpdate, Network } from '@ton/walletkit'; import type { AppKit } from '../../core/app-kit'; +import type { BalanceUpdate } from '../../core/streaming'; +import type { UserFriendlyAddress } from '../../types/primitives'; +import type { Network } from '../../types/network'; import { resolveNetwork } from '../../utils/network/resolve-network'; +/** + * Options for {@link watchBalanceByAddress}. + * + * @public + * @category Type + * @section Balances + */ export interface WatchBalanceByAddressOptions { - address: string | Address; + /** Wallet address — pass a {@link UserFriendlyAddress} string or an `Address` instance from `@ton/core`. */ + address: UserFriendlyAddress | Address; + /** Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; + /** Callback fired on every balance update from the streaming provider. */ onChange: (update: BalanceUpdate) => void; } +/** + * Return type of {@link watchBalanceByAddress} — call to stop receiving updates. + * + * @public + * @category Type + * @section Balances + */ export type WatchBalanceByAddressReturnType = () => void; /** - * Watch account balance changes by address. + * Subscribe to Toncoin balance updates for an arbitrary address — useful for monitoring wallets that aren't selected in AppKit (use {@link watchBalance} for the selected wallet). Requires a streaming provider registered for the network — call throws when none is configured. Use {@link hasStreamingProvider} to check first. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link WatchBalanceByAddressOptions} Target address, update callback and optional network override. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @sample docs/examples/src/appkit/actions/balances#WATCH_BALANCE_BY_ADDRESS + * @expand options + * + * @public + * @category Action + * @section Balances */ export const watchBalanceByAddress = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/balances/watch-balance.ts b/packages/appkit/src/actions/balances/watch-balance.ts index e8ff00a60..14764be35 100644 --- a/packages/appkit/src/actions/balances/watch-balance.ts +++ b/packages/appkit/src/actions/balances/watch-balance.ts @@ -6,22 +6,49 @@ * */ -import type { BalanceUpdate, Network } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; import { WALLETS_EVENTS } from '../../core/app-kit'; +import type { BalanceUpdate } from '../../core/streaming'; +import type { Network } from '../../types/network'; import { getSelectedWallet } from '../wallets/get-selected-wallet'; import { watchBalanceByAddress } from './watch-balance-by-address'; +/** + * Options for {@link watchBalance}. + * + * @public + * @category Type + * @section Balances + */ export interface WatchBalanceOptions { + /** Network to watch on. Defaults to the selected wallet's network. */ network?: Network; + /** Callback fired on every balance update from the streaming provider. */ onChange: (update: BalanceUpdate) => void; } +/** + * Return type of {@link watchBalance} — call to stop receiving updates. + * + * @public + * @category Type + * @section Balances + */ export type WatchBalanceReturnType = () => void; /** - * Watch account balance changes for the selected wallet. + * Subscribe to Toncoin balance updates for the currently selected wallet, automatically rebinding whenever the selected wallet changes or the connected-wallets list updates (use {@link watchBalanceByAddress} for a fixed address). Requires a streaming provider registered for the network — call throws when none is configured. Use {@link hasStreamingProvider} to check first. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link WatchBalanceOptions} Update callback and optional network override. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @sample docs/examples/src/appkit/actions/balances#WATCH_BALANCE + * @expand options + * + * @public + * @category Action + * @section Balances */ export const watchBalance = (appKit: AppKit, options: WatchBalanceOptions): WatchBalanceReturnType => { const { network, onChange } = options; diff --git a/packages/appkit/src/actions/connectors/add-connector.ts b/packages/appkit/src/actions/connectors/add-connector.ts index 36121b536..a02629483 100644 --- a/packages/appkit/src/actions/connectors/add-connector.ts +++ b/packages/appkit/src/actions/connectors/add-connector.ts @@ -9,13 +9,37 @@ import type { AppKit } from '../../core/app-kit'; import type { ConnectorInput } from '../../types/connector'; +/** + * Connector instance or factory accepted by {@link addConnector} — same shape used in {@link AppKitConfig}'s `connectors`. + * + * @public + * @category Type + * @section Connectors + */ export type AddConnectorParameters = ConnectorInput; +/** + * Return type of {@link addConnector} — call to remove the connector from AppKit. + * + * @public + * @category Type + * @section Connectors + */ export type AddConnectorReturnType = () => void; /** - * Add a wallet connector + * Register a wallet connector at runtime — equivalent to passing it via {@link AppKitConfig}'s `connectors` at construction, but available after AppKit is up. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param connector - {@link AddConnectorParameters} Connector instance or factory to register. + * @returns Function that unregisters the connector when called. + * + * @sample docs/examples/src/appkit/actions/connectors#ADD_CONNECTOR + * + * @public + * @category Action + * @section Connectors */ -export const addConnector = (appKit: AppKit, connectorFn: AddConnectorParameters): AddConnectorReturnType => { - return appKit.addConnector(connectorFn); +export const addConnector = (appKit: AppKit, connector: AddConnectorParameters): AddConnectorReturnType => { + return appKit.addConnector(connector); }; diff --git a/packages/appkit/src/actions/connectors/connect.ts b/packages/appkit/src/actions/connectors/connect.ts index 199d6bb7c..a5521e075 100644 --- a/packages/appkit/src/actions/connectors/connect.ts +++ b/packages/appkit/src/actions/connectors/connect.ts @@ -9,14 +9,40 @@ import type { AppKit } from '../../core/app-kit'; import { getDefaultNetwork } from '../network/get-default-network'; +/** + * Parameters accepted by {@link connect}. + * + * @public + * @category Type + * @section Connectors + */ export type ConnectParameters = { + /** ID of the registered connector to drive the connection through (e.g., `'tonconnect'`). */ connectorId: string; }; +/** + * Return type of {@link connect}. + * + * @public + * @category Type + * @section Connectors + */ export type ConnectReturnType = void; /** - * Connect wallet using specific connector + * Trigger the connection flow on a registered connector by id — drives it against AppKit's default network (set via {@link setDefaultNetwork}). Throws when no connector with that id exists. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link ConnectParameters} Connector to connect through. + * @returns Resolves once the connector's connect flow completes. If a wallet was successfully connected, it becomes available via {@link getSelectedWallet}. + * + * @sample docs/examples/src/appkit/actions/connectors#CONNECT + * @expand parameters + * + * @public + * @category Action + * @section Connectors */ export const connect = async (appKit: AppKit, parameters: ConnectParameters): Promise => { const { connectorId } = parameters; diff --git a/packages/appkit/src/actions/connectors/disconnect.ts b/packages/appkit/src/actions/connectors/disconnect.ts index 4fdd0db2d..41c53c06f 100644 --- a/packages/appkit/src/actions/connectors/disconnect.ts +++ b/packages/appkit/src/actions/connectors/disconnect.ts @@ -8,14 +8,40 @@ import type { AppKit } from '../../core/app-kit'; +/** + * Parameters accepted by {@link disconnect}. + * + * @public + * @category Type + * @section Connectors + */ export type DisconnectParameters = { + /** ID of the registered connector whose wallet should be disconnected. */ connectorId: string; }; +/** + * Return type of {@link disconnect}. + * + * @public + * @category Type + * @section Connectors + */ export type DisconnectReturnType = void; /** - * Disconnect wallet using specific connector + * Tear down the session on a registered connector — disconnects the wallet currently connected through it, if any. Throws when no connector with that id exists. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link DisconnectParameters} Connector to disconnect. + * @returns Resolves once the connector tears down its session. + * + * @sample docs/examples/src/appkit/actions/connectors#DISCONNECT + * @expand parameters + * + * @public + * @category Action + * @section Connectors */ export const disconnect = async (appKit: AppKit, parameters: DisconnectParameters): Promise => { const { connectorId } = parameters; diff --git a/packages/appkit/src/actions/connectors/get-connector-by-id.ts b/packages/appkit/src/actions/connectors/get-connector-by-id.ts index 9bd3263f2..15bccafda 100644 --- a/packages/appkit/src/actions/connectors/get-connector-by-id.ts +++ b/packages/appkit/src/actions/connectors/get-connector-by-id.ts @@ -9,14 +9,40 @@ import type { Connector } from '../../types/connector'; import type { AppKit } from '../../core/app-kit'; +/** + * Options for {@link getConnectorById}. + * + * @public + * @category Type + * @section Connectors + */ export interface GetConnectorByIdOptions { + /** ID of the connector to look up. */ id: string; } +/** + * Return type of {@link getConnectorById} — `undefined` when no connector with that id is registered. + * + * @public + * @category Type + * @section Connectors + */ export type GetConnectorByIdReturnType = Connector | undefined; /** - * Get connector by id + * Look up a registered connector by its id. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetConnectorByIdOptions} ID of the connector to find. + * @returns The matching {@link Connector}, or `undefined` if none with that id is registered. + * + * @sample docs/examples/src/appkit/actions/connectors#GET_CONNECTOR_BY_ID + * @expand options + * + * @public + * @category Action + * @section Connectors */ export const getConnectorById = (appKit: AppKit, options: GetConnectorByIdOptions): GetConnectorByIdReturnType => { return appKit.connectors.find((connector) => connector.id === options.id); diff --git a/packages/appkit/src/actions/connectors/get-connectors.ts b/packages/appkit/src/actions/connectors/get-connectors.ts index 5f9adae9a..a82fad9aa 100644 --- a/packages/appkit/src/actions/connectors/get-connectors.ts +++ b/packages/appkit/src/actions/connectors/get-connectors.ts @@ -9,10 +9,26 @@ import type { Connector } from '../../types/connector'; import type { AppKit } from '../../core/app-kit'; +/** + * Return type of {@link getConnectors} — read-only view of the registered-connectors array. + * + * @public + * @category Type + * @section Connectors + */ export type GetConnectorsReturnType = readonly Connector[]; /** - * Get connected wallets + * List every connector registered on this AppKit instance — both those passed via {@link AppKitConfig}'s `connectors` and those added later through {@link addConnector}. + * + * @param appKit - {@link AppKit} Runtime instance. + * @returns Read-only array of registered {@link Connector}s. + * + * @sample docs/examples/src/appkit/actions/connectors#GET_CONNECTORS + * + * @public + * @category Action + * @section Connectors */ export const getConnectors = (appKit: AppKit): GetConnectorsReturnType => { return appKit.connectors; diff --git a/packages/appkit/src/actions/connectors/watch-connector-by-id.ts b/packages/appkit/src/actions/connectors/watch-connector-by-id.ts index 757ec9ce9..accff17bb 100644 --- a/packages/appkit/src/actions/connectors/watch-connector-by-id.ts +++ b/packages/appkit/src/actions/connectors/watch-connector-by-id.ts @@ -11,15 +11,42 @@ import { CONNECTOR_EVENTS } from '../../core/app-kit'; import type { Connector } from '../../types/connector'; import { getConnectorById } from './get-connector-by-id'; +/** + * Parameters accepted by {@link watchConnectorById}. + * + * @public + * @category Type + * @section Connectors + */ export interface WatchConnectorByIdParameters { + /** ID of the connector to watch. */ id: string; + /** Callback invoked when the connector with the watched id is registered or unregistered — receives the connector itself, or `undefined` when none is registered under that id. */ onChange: (connector: Connector | undefined) => void; } +/** + * Return type of {@link watchConnectorById} — call to stop receiving updates. + * + * @public + * @category Type + * @section Connectors + */ export type WatchConnectorByIdReturnType = () => void; /** - * Watch connector by id + * Subscribe to register/unregister events for a connector with the given id — the callback fires when the connector is added or removed, so callers can react to its presence. Use {@link watchConnectedWallets} if you want to react to wallet connect/disconnect events instead. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link WatchConnectorByIdParameters} Connector ID and update callback. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @sample docs/examples/src/appkit/actions/connectors#WATCH_CONNECTOR_BY_ID + * @expand parameters + * + * @public + * @category Action + * @section Connectors */ export const watchConnectorById = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/connectors/watch-connectors.ts b/packages/appkit/src/actions/connectors/watch-connectors.ts index eabe24535..31a135d92 100644 --- a/packages/appkit/src/actions/connectors/watch-connectors.ts +++ b/packages/appkit/src/actions/connectors/watch-connectors.ts @@ -11,14 +11,40 @@ import { CONNECTOR_EVENTS } from '../../core/app-kit'; import type { Connector } from '../../types/connector'; import { getConnectors } from './get-connectors'; +/** + * Parameters accepted by {@link watchConnectors}. + * + * @public + * @category Type + * @section Connectors + */ export type WatchConnectorsParameters = { + /** Callback invoked when the list of registered connectors changes — receives the current list. */ onChange: (connectors: readonly Connector[]) => void; }; +/** + * Return type of {@link watchConnectors} — call to stop receiving updates. + * + * @public + * @category Type + * @section Connectors + */ export type WatchConnectorsReturnType = () => void; /** - * Watch connectors + * Subscribe to changes in the registered-connectors list — the callback fires when a connector is added (via {@link addConnector} or AppKit's constructor) or removed, and receives the current list. Use {@link watchConnectedWallets} if you want to react to wallet connect/disconnect events instead. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link WatchConnectorsParameters} Update callback. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @sample docs/examples/src/appkit/actions/connectors#WATCH_CONNECTORS + * @expand parameters + * + * @public + * @category Action + * @section Connectors */ export const watchConnectors = (appKit: AppKit, parameters: WatchConnectorsParameters): WatchConnectorsReturnType => { const { onChange } = parameters; diff --git a/packages/appkit/src/actions/crypto-onramp/create-crypto-onramp-deposit.ts b/packages/appkit/src/actions/crypto-onramp/create-crypto-onramp-deposit.ts index 8796a42b4..0bbece461 100644 --- a/packages/appkit/src/actions/crypto-onramp/create-crypto-onramp-deposit.ts +++ b/packages/appkit/src/actions/crypto-onramp/create-crypto-onramp-deposit.ts @@ -9,14 +9,39 @@ import type { CryptoOnrampDeposit, CryptoOnrampDepositParams } from '../../crypto-onramp'; import type { AppKit } from '../../core/app-kit'; +/** + * Options for {@link createCryptoOnrampDeposit} — extends {@link CryptoOnrampDepositParams} with an optional provider override. + * + * @public + * @category Type + * @section Crypto Onramp + */ export type CreateCryptoOnrampDepositOptions = CryptoOnrampDepositParams & { + /** Provider to create the deposit through. Defaults to `quote.providerId`, then to the default provider. */ providerId?: string; }; +/** + * Return type of {@link createCryptoOnrampDeposit}. + * + * @public + * @category Type + * @section Crypto Onramp + */ export type CreateCryptoOnrampDepositReturnType = Promise; /** - * Create a crypto onramp deposit from a previously obtained quote + * Create a crypto-onramp deposit from a quote previously obtained via {@link getCryptoOnrampQuote} — the returned {@link CryptoOnrampDeposit} carries the address and amount the user must send on the source chain. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link CreateCryptoOnrampDepositOptions} Quote, refund address, and optional provider override. + * @returns Deposit details the UI should show to the user (address, amount, optional `memo`/`expiresAt`). + * + * @expand options + * + * @public + * @category Action + * @section Crypto Onramp */ export const createCryptoOnrampDeposit = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-provider.ts b/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-provider.ts index 47cf0a91f..65ef5d03d 100644 --- a/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-provider.ts +++ b/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-provider.ts @@ -6,18 +6,43 @@ * */ -import type { CryptoOnrampProviderInterface } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { CryptoOnrampProviderInterface } from '../../crypto-onramp'; +/** + * Options for {@link getCryptoOnrampProvider}. + * + * @public + * @category Type + * @section Crypto Onramp + */ export interface GetCryptoOnrampProviderOptions { + /** Provider ID to look up. When omitted, returns the registered default provider. */ id?: string; } +/** + * Return type of {@link getCryptoOnrampProvider}. + * + * @public + * @category Type + * @section Crypto Onramp + */ export type GetCryptoOnrampProviderReturnType = CryptoOnrampProviderInterface; /** - * Get a registered crypto-onramp provider by id, or the default one when no id is given. + * Get a registered crypto-onramp provider by id, or the default provider when no id is given. Throws when no provider matches — or when no id is passed and no default has been registered. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetCryptoOnrampProviderOptions} Optional provider id. + * @returns The matching {@link CryptoOnrampProviderInterface}. + * + * @sample docs/examples/src/appkit/actions/onramp#GET_CRYPTO_ONRAMP_PROVIDER + * @expand options + * + * @public + * @category Action + * @section Crypto Onramp */ export const getCryptoOnrampProvider = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-providers.ts b/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-providers.ts index ea4add53b..b14de4f8b 100644 --- a/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-providers.ts +++ b/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-providers.ts @@ -6,14 +6,29 @@ * */ -import type { CryptoOnrampProviderInterface } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { CryptoOnrampProviderInterface } from '../../crypto-onramp'; +/** + * Return type of {@link getCryptoOnrampProviders}. + * + * @public + * @category Type + * @section Crypto Onramp + */ export type GetCryptoOnrampProvidersReturnType = CryptoOnrampProviderInterface[]; /** - * Get all registered crypto-onramp providers. + * List every crypto-onramp provider registered on this AppKit instance — both those passed via {@link AppKitConfig}'s `providers` and those added later through {@link registerProvider}. + * + * @param appKit - {@link AppKit} Runtime instance. + * @returns Array of registered {@link CryptoOnrampProviderInterface}s. + * + * @sample docs/examples/src/appkit/actions/onramp#GET_CRYPTO_ONRAMP_PROVIDERS + * + * @public + * @category Action + * @section Crypto Onramp */ export const getCryptoOnrampProviders = (appKit: AppKit): GetCryptoOnrampProvidersReturnType => { return appKit.cryptoOnrampManager.getProviders(); diff --git a/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-quote.ts b/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-quote.ts index 32fee07da..84783d3ea 100644 --- a/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-quote.ts +++ b/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-quote.ts @@ -9,14 +9,39 @@ import type { CryptoOnrampQuote, CryptoOnrampQuoteParams } from '../../crypto-onramp'; import type { AppKit } from '../../core/app-kit'; +/** + * Options for {@link getCryptoOnrampQuote} — extends {@link CryptoOnrampQuoteParams} with an optional provider override. + * + * @public + * @category Type + * @section Crypto Onramp + */ export type GetCryptoOnrampQuoteOptions = CryptoOnrampQuoteParams & { + /** Provider to quote against. Defaults to the registered default provider. */ providerId?: string; }; +/** + * Return type of {@link getCryptoOnrampQuote}. + * + * @public + * @category Type + * @section Crypto Onramp + */ export type GetCryptoOnrampQuoteReturnType = Promise; /** - * Get a crypto onramp quote + * Quote a crypto-to-TON onramp — given a source asset/chain and target TON asset, returns the rate, expected amount, and provider metadata needed to call {@link createCryptoOnrampDeposit}. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetCryptoOnrampQuoteOptions} Source asset, target asset, amount and optional provider override. + * @returns Quote with pricing details and the provider metadata required to create a deposit. + * + * @expand options + * + * @public + * @category Action + * @section Crypto Onramp */ export const getCryptoOnrampQuote = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-status.ts b/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-status.ts index 7be56078d..e256b6ee7 100644 --- a/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-status.ts +++ b/packages/appkit/src/actions/crypto-onramp/get-crypto-onramp-status.ts @@ -9,14 +9,39 @@ import type { CryptoOnrampStatus, CryptoOnrampStatusParams } from '../../crypto-onramp'; import type { AppKit } from '../../core/app-kit'; +/** + * Options for {@link getCryptoOnrampStatus} — extends {@link CryptoOnrampStatusParams} with an optional provider override. + * + * @public + * @category Type + * @section Crypto Onramp + */ export type GetCryptoOnrampStatusOptions = CryptoOnrampStatusParams & { + /** Provider that issued the deposit. Defaults to the registered default provider. */ providerId?: string; }; +/** + * Return type of {@link getCryptoOnrampStatus}. + * + * @public + * @category Type + * @section Crypto Onramp + */ export type GetCryptoOnrampStatusReturnType = Promise; /** - * Get a crypto onramp quote + * Read the current status of a crypto-onramp deposit by id — typically polled until the result is `'success'` or `'failed'`. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetCryptoOnrampStatusOptions} Deposit id, originating provider id and optional provider override. + * @returns Current {@link CryptoOnrampStatus} of the deposit. + * + * @expand options + * + * @public + * @category Action + * @section Crypto Onramp */ export const getCryptoOnrampStatus = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/crypto-onramp/watch-crypto-onramp-providers.ts b/packages/appkit/src/actions/crypto-onramp/watch-crypto-onramp-providers.ts index dea15b8eb..6f40dfb8a 100644 --- a/packages/appkit/src/actions/crypto-onramp/watch-crypto-onramp-providers.ts +++ b/packages/appkit/src/actions/crypto-onramp/watch-crypto-onramp-providers.ts @@ -8,14 +8,39 @@ import type { AppKit } from '../../core/app-kit'; +/** + * Parameters accepted by {@link watchCryptoOnrampProviders}. + * + * @public + * @category Type + * @section Crypto Onramp + */ export interface WatchCryptoOnrampProvidersParameters { + /** Callback fired whenever a crypto-onramp provider is registered or the default crypto-onramp provider changes. */ onChange: () => void; } +/** + * Return type of {@link watchCryptoOnrampProviders} — call to stop receiving updates. + * + * @public + * @category Type + * @section Crypto Onramp + */ export type WatchCryptoOnrampProvidersReturnType = () => void; /** - * Watch for new crypto-onramp providers registration and default-provider changes. + * Subscribe to crypto-onramp provider lifecycle — fires `onChange` whenever a new provider is registered or the default crypto-onramp provider switches. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link WatchCryptoOnrampProvidersParameters} Update callback. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @expand parameters + * + * @public + * @category Action + * @section Crypto Onramp */ export const watchCryptoOnrampProviders = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/index.ts b/packages/appkit/src/actions/index.ts index b9d31916d..dc7b8025d 100644 --- a/packages/appkit/src/actions/index.ts +++ b/packages/appkit/src/actions/index.ts @@ -41,7 +41,7 @@ export { type WatchConnectorByIdReturnType, } from './connectors/watch-connector-by-id'; -// Crypto onramp +// Crypto Onramp export { getCryptoOnrampProvider, type GetCryptoOnrampProviderOptions, diff --git a/packages/appkit/src/actions/jettons/create-transfer-jetton-transaction.ts b/packages/appkit/src/actions/jettons/create-transfer-jetton-transaction.ts index bd4b818f9..06d47647e 100644 --- a/packages/appkit/src/actions/jettons/create-transfer-jetton-transaction.ts +++ b/packages/appkit/src/actions/jettons/create-transfer-jetton-transaction.ts @@ -6,30 +6,60 @@ * */ +import type { AppKit } from '../../core/app-kit'; +import type { TransactionRequest } from '../../types/transaction'; +import type { UserFriendlyAddress } from '../../types/primitives'; import { createJettonTransferPayload, createTransferTransaction, getJettonWalletAddressFromClient, DEFAULT_JETTON_GAS_FEE, parseUnits, -} from '@ton/walletkit'; - -import type { TransactionRequest } from '../../types/transaction'; -import type { AppKit } from '../../core/app-kit'; +} from '../../utils'; import { getSelectedWallet } from '../wallets/get-selected-wallet'; +/** + * Parameters accepted by {@link createTransferJettonTransaction} and {@link transferJetton}. + * + * @public + * @category Type + * @section Jettons + */ export interface CreateTransferJettonTransactionParameters { - jettonAddress: string; - recipientAddress: string; + /** Jetton master contract address being transferred. */ + jettonAddress: UserFriendlyAddress; + /** Recipient who should receive the jettons. */ + recipientAddress: UserFriendlyAddress; + /** Amount in jetton units as a human-readable decimal string (e.g., `"1.5"`). */ amount: string; + /** Decimals declared by the jetton master. Used to convert `amount` into raw smallest units. */ jettonDecimals: number; + /** Optional human-readable comment attached to the transfer. */ comment?: string; } +/** + * Return type of {@link createTransferJettonTransaction}. + * + * @public + * @category Type + * @section Jettons + */ export type CreateTransferJettonTransactionReturnType = TransactionRequest; /** - * Create a Jetton transfer transaction request + * Build a jetton transfer {@link TransactionRequest} for the selected wallet without sending it — useful when the UI needs to inspect or batch transactions before signing. Throws `Error('Wallet not connected')` if no wallet is currently selected. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link CreateTransferJettonTransactionParameters} Jetton, recipient, amount, decimals and optional comment. + * @returns Transaction request ready to pass to `sendTransaction`. + * + * @sample docs/examples/src/appkit/actions/jettons#CREATE_TRANSFER_JETTON_TRANSACTION + * @expand parameters + * + * @public + * @category Action + * @section Jettons */ export const createTransferJettonTransaction = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/jettons/get-jetton-balance.ts b/packages/appkit/src/actions/jettons/get-jetton-balance.ts index c59531add..cdce6465e 100644 --- a/packages/appkit/src/actions/jettons/get-jetton-balance.ts +++ b/packages/appkit/src/actions/jettons/get-jetton-balance.ts @@ -6,23 +6,54 @@ * */ -import { getJettonBalanceFromClient, formatUnits } from '@ton/walletkit'; -import type { TokenAmount, UserFriendlyAddress } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; -import { getJettonWalletAddress } from './get-jetton-wallet-address'; -import { resolveNetwork } from '../../utils/network/resolve-network'; +import type { TokenAmount, UserFriendlyAddress } from '../../types/primitives'; import type { Network } from '../../types/network'; +import { getJettonBalanceFromClient, formatUnits } from '../../utils'; +import { resolveNetwork } from '../../utils/network/resolve-network'; +import { getJettonWalletAddress } from './get-jetton-wallet-address'; +/** + * Options for {@link getJettonBalance}. + * + * @public + * @category Type + * @section Jettons + */ export interface GetJettonBalanceOptions { + /** Jetton master contract address (the token, not the user's wallet for it). */ jettonAddress: UserFriendlyAddress; + /** Owner of the jetton wallet — typically the connected user's address. */ ownerAddress: UserFriendlyAddress; + /** Decimals declared by the jetton master. Used to format the raw balance into a human-readable string. */ jettonDecimals: number; + /** Network to read the balance from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; } +/** + * Return type of {@link getJettonBalance}. + * + * @public + * @category Type + * @section Jettons + */ export type GetJettonBalanceReturnType = TokenAmount; +/** + * Read a jetton balance for a given owner — derives the owner's jetton-wallet address from the master, then fetches and formats the balance using the supplied decimals. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetJettonBalanceOptions} Jetton master, owner address, decimals and optional network override. + * @returns Balance as a human-readable decimal string in the jetton's units. + * + * @sample docs/examples/src/appkit/actions/jettons#GET_JETTON_BALANCE + * @expand options + * + * @public + * @category Action + * @section Jettons + */ export const getJettonBalance = async ( appKit: AppKit, options: GetJettonBalanceOptions, diff --git a/packages/appkit/src/actions/jettons/get-jetton-info.ts b/packages/appkit/src/actions/jettons/get-jetton-info.ts index a2681f5a0..8c516fb32 100644 --- a/packages/appkit/src/actions/jettons/get-jetton-info.ts +++ b/packages/appkit/src/actions/jettons/get-jetton-info.ts @@ -6,19 +6,49 @@ * */ -import type { JettonInfo } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; -import { resolveNetwork } from '../../utils/network/resolve-network'; +import type { JettonInfo } from '../../types/jetton'; import type { Network } from '../../types/network'; +import type { UserFriendlyAddress } from '../../types/primitives'; +import { resolveNetwork } from '../../utils/network/resolve-network'; +/** + * Options for {@link getJettonInfo}. + * + * @public + * @category Type + * @section Jettons + */ export interface GetJettonInfoOptions { - address: string; + /** Jetton master contract address whose metadata is being fetched. */ + address: UserFriendlyAddress; + /** Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; } +/** + * Return type of {@link getJettonInfo} — `null` when the indexer has no record for that master address. + * + * @public + * @category Type + * @section Jettons + */ export type GetJettonInfoReturnType = JettonInfo | null; +/** + * Fetch token metadata for a jetton master — name, symbol, decimals, image and description as reported by the indexer. Returns `null` when the indexer has no record for that master address. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetJettonInfoOptions} Jetton master address and optional network override. + * @returns Jetton metadata, or `null` if the indexer has no record. + * + * @sample docs/examples/src/appkit/actions/jettons#GET_JETTON_INFO + * @expand options + * + * @public + * @category Action + * @section Jettons + */ export const getJettonInfo = async ( appKit: AppKit, options: GetJettonInfoOptions, diff --git a/packages/appkit/src/actions/jettons/get-jetton-wallet-address.ts b/packages/appkit/src/actions/jettons/get-jetton-wallet-address.ts index 5fbd9d294..815817904 100644 --- a/packages/appkit/src/actions/jettons/get-jetton-wallet-address.ts +++ b/packages/appkit/src/actions/jettons/get-jetton-wallet-address.ts @@ -6,21 +6,51 @@ * */ -import { getJettonWalletAddressFromClient } from '@ton/walletkit'; -import type { UserFriendlyAddress } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; -import { resolveNetwork } from '../../utils/network/resolve-network'; +import type { UserFriendlyAddress } from '../../types/primitives'; import type { Network } from '../../types/network'; +import { getJettonWalletAddressFromClient } from '../../utils'; +import { resolveNetwork } from '../../utils/network/resolve-network'; +/** + * Options for {@link getJettonWalletAddress}. + * + * @public + * @category Type + * @section Jettons + */ export interface GetJettonWalletAddressOptions { + /** Jetton master contract address. */ jettonAddress: UserFriendlyAddress; + /** Owner whose jetton wallet should be derived. */ ownerAddress: UserFriendlyAddress; + /** Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; } +/** + * Return type of {@link getJettonWalletAddress}. + * + * @public + * @category Type + * @section Jettons + */ export type GetJettonWalletAddressReturnType = UserFriendlyAddress; +/** + * Derive the jetton-wallet address for a given owner — the per-owner contract that actually holds the jetton balance for `jettonAddress`. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetJettonWalletAddressOptions} Jetton master, owner address and optional network override. + * @returns User-friendly address of the owner's jetton wallet. + * + * @sample docs/examples/src/appkit/actions/jettons#GET_JETTON_WALLET_ADDRESS + * @expand options + * + * @public + * @category Action + * @section Jettons + */ export const getJettonWalletAddress = async ( appKit: AppKit, options: GetJettonWalletAddressOptions, diff --git a/packages/appkit/src/actions/jettons/get-jettons-by-address.ts b/packages/appkit/src/actions/jettons/get-jettons-by-address.ts index 808cae0e4..d7ab7ff80 100644 --- a/packages/appkit/src/actions/jettons/get-jettons-by-address.ts +++ b/packages/appkit/src/actions/jettons/get-jettons-by-address.ts @@ -7,22 +7,55 @@ */ import { Address } from '@ton/core'; -import type { Jetton, JettonsResponse } from '@ton/walletkit'; -import { getJettonsFromClient, formatUnits } from '@ton/walletkit'; import type { AppKit } from '../../core/app-kit'; -import { resolveNetwork } from '../../utils/network/resolve-network'; +import type { Jetton, JettonsResponse } from '../../types/jetton'; import type { Network } from '../../types/network'; +import type { UserFriendlyAddress } from '../../types/primitives'; +import { getJettonsFromClient, formatUnits } from '../../utils'; +import { resolveNetwork } from '../../utils/network/resolve-network'; +/** + * Options for {@link getJettonsByAddress}. + * + * @public + * @category Type + * @section Jettons + */ export interface GetJettonsByAddressOptions { - address: string | Address; + /** Owner address — pass a {@link UserFriendlyAddress} string or an `Address` instance from `@ton/core`. */ + address: UserFriendlyAddress | Address; + /** Network to read the jettons from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; + /** Maximum number of jettons to return. */ limit?: number; + /** Number of jettons to skip before returning results — used for pagination. */ offset?: number; } +/** + * Return type of {@link getJettonsByAddress}. + * + * @public + * @category Type + * @section Jettons + */ export type GetJettonsByAddressReturnType = JettonsResponse; +/** + * List jettons held by an arbitrary address — useful for inspecting wallets that aren't selected in AppKit (use {@link getJettons} for the selected wallet). Raw balances are formatted with each jetton's declared decimals, and entries without decimals are dropped. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetJettonsByAddressOptions} Owner address, optional network override and pagination. + * @returns Jettons response with formatted balances. + * + * @sample docs/examples/src/appkit/actions/jettons#GET_JETTONS_BY_ADDRESS + * @expand options + * + * @public + * @category Action + * @section Jettons + */ export const getJettonsByAddress = async ( appKit: AppKit, options: GetJettonsByAddressOptions, diff --git a/packages/appkit/src/actions/jettons/get-jettons.ts b/packages/appkit/src/actions/jettons/get-jettons.ts index 5f662a894..1cac6fbec 100644 --- a/packages/appkit/src/actions/jettons/get-jettons.ts +++ b/packages/appkit/src/actions/jettons/get-jettons.ts @@ -6,21 +6,51 @@ * */ -import type { JettonsResponse } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; -import { getJettonsByAddress } from './get-jettons-by-address'; -import { getSelectedWallet } from '../wallets/get-selected-wallet'; +import type { JettonsResponse } from '../../types/jetton'; import type { Network } from '../../types/network'; +import { getSelectedWallet } from '../wallets/get-selected-wallet'; +import { getJettonsByAddress } from './get-jettons-by-address'; +/** + * Options for {@link getJettons}. + * + * @public + * @category Type + * @section Jettons + */ export interface GetJettonsOptions { + /** Network to read jettons from. Defaults to the selected wallet's network. */ network?: Network; + /** Maximum number of jettons to return. */ limit?: number; + /** Number of jettons to skip before returning results — used for pagination. */ offset?: number; } +/** + * Return type of {@link getJettons} — `null` when no wallet is currently selected. + * + * @public + * @category Type + * @section Jettons + */ export type GetJettonsReturnType = JettonsResponse | null; +/** + * List jettons held by the currently selected wallet, returning `null` when no wallet is selected (use {@link getJettonsByAddress} for an arbitrary address). + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetJettonsOptions} Optional network override and pagination. + * @returns Jettons response for the selected wallet, or `null` when none is selected. + * + * @sample docs/examples/src/appkit/actions/jettons#GET_JETTONS + * @expand options + * + * @public + * @category Action + * @section Jettons + */ export const getJettons = async (appKit: AppKit, options: GetJettonsOptions = {}): Promise => { const selectedWallet = getSelectedWallet(appKit); diff --git a/packages/appkit/src/actions/jettons/transfer-jetton.ts b/packages/appkit/src/actions/jettons/transfer-jetton.ts index 01f17501d..0bdae9de1 100644 --- a/packages/appkit/src/actions/jettons/transfer-jetton.ts +++ b/packages/appkit/src/actions/jettons/transfer-jetton.ts @@ -6,21 +6,45 @@ * */ -import type { SendTransactionResponse } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { SendTransactionResponse } from '../../types/transaction'; +import { sendTransaction } from '../transaction/send-transaction'; import { createTransferJettonTransaction } from './create-transfer-jetton-transaction'; import type { CreateTransferJettonTransactionParameters } from './create-transfer-jetton-transaction'; -import { sendTransaction } from '../transaction/send-transaction'; +/** + * Parameters accepted by {@link transferJetton} — same shape as {@link CreateTransferJettonTransactionParameters}. + * + * @public + * @category Type + * @section Jettons + */ export type TransferJettonParameters = CreateTransferJettonTransactionParameters; +/** + * Return type of {@link transferJetton}. + * + * @public + * @category Type + * @section Jettons + */ export type TransferJettonReturnType = SendTransactionResponse; export type TransferJettonErrorType = Error; /** - * Transfer Jetton - creates and sends a Jetton transfer transaction + * Build and send a jetton transfer from the selected wallet in one step (use {@link createTransferJettonTransaction} + {@link sendTransaction} if you need to inspect the transaction first). Throws `Error('Wallet not connected')` if no wallet is currently selected. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link TransferJettonParameters} Jetton, recipient, amount, decimals and optional comment. + * @returns Wallet response carrying the BoC of the sent transaction. + * + * @sample docs/examples/src/appkit/actions/jettons#TRANSFER_JETTON + * @expand parameters + * + * @public + * @category Action + * @section Jettons */ export const transferJetton = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/jettons/watch-jettons-by-address.ts b/packages/appkit/src/actions/jettons/watch-jettons-by-address.ts index 0cd80d9c9..d1b676544 100644 --- a/packages/appkit/src/actions/jettons/watch-jettons-by-address.ts +++ b/packages/appkit/src/actions/jettons/watch-jettons-by-address.ts @@ -7,21 +7,50 @@ */ import { Address } from '@ton/core'; -import type { JettonUpdate, Network } from '@ton/walletkit'; import type { AppKit } from '../../core/app-kit'; +import type { JettonUpdate } from '../../core/streaming'; +import type { Network } from '../../types/network'; +import type { UserFriendlyAddress } from '../../types/primitives'; import { resolveNetwork } from '../../utils/network/resolve-network'; +/** + * Options for {@link watchJettonsByAddress}. + * + * @public + * @category Type + * @section Jettons + */ export interface WatchJettonsByAddressOptions { - address: string | Address; + /** Owner address — pass a {@link UserFriendlyAddress} string or an `Address` instance from `@ton/core`. */ + address: UserFriendlyAddress | Address; + /** Callback fired on every jetton-balance update from the streaming provider. */ onChange: (update: JettonUpdate) => void; + /** Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; } +/** + * Return type of {@link watchJettonsByAddress} — call to stop receiving updates. + * + * @public + * @category Type + * @section Jettons + */ export type WatchJettonsByAddressReturnType = () => void; /** - * Watch jetton updates by owner address. + * Subscribe to jetton-balance updates for an arbitrary owner address (use {@link watchJettons} for the selected wallet). Requires a streaming provider registered for the network — call throws when none is configured. Use {@link hasStreamingProvider} to check first. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link WatchJettonsByAddressOptions} Owner address, update callback and optional network override. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @expand options + * + * @public + * @category Action + * @section Jettons */ export const watchJettonsByAddress = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/jettons/watch-jettons.ts b/packages/appkit/src/actions/jettons/watch-jettons.ts index db8eb3fd3..9deda60ba 100644 --- a/packages/appkit/src/actions/jettons/watch-jettons.ts +++ b/packages/appkit/src/actions/jettons/watch-jettons.ts @@ -6,22 +6,48 @@ * */ -import type { JettonUpdate, Network } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; import { WALLETS_EVENTS } from '../../core/app-kit'; +import type { JettonUpdate } from '../../core/streaming'; +import type { Network } from '../../types/network'; import { getSelectedWallet } from '../wallets/get-selected-wallet'; import { watchJettonsByAddress } from './watch-jettons-by-address'; +/** + * Options for {@link watchJettons}. + * + * @public + * @category Type + * @section Jettons + */ export interface WatchJettonsOptions { + /** Callback fired on every jetton-balance update from the streaming provider. */ onChange: (update: JettonUpdate) => void; + /** Network to watch on. Defaults to the selected wallet's network. */ network?: Network; } +/** + * Return type of {@link watchJettons} — call to stop receiving updates. + * + * @public + * @category Type + * @section Jettons + */ export type WatchJettonsReturnType = () => void; /** - * Watch jetton updates for the selected wallet. + * Subscribe to jetton-balance updates for the currently selected wallet, automatically rebinding when the user connects, switches, or disconnects (use {@link watchJettonsByAddress} for a fixed address). Requires a streaming provider registered for the network — call throws when none is configured. Use {@link hasStreamingProvider} to check first. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link WatchJettonsOptions} Update callback and optional network override. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @expand options + * + * @public + * @category Action + * @section Jettons */ export const watchJettons = (appKit: AppKit, options: WatchJettonsOptions): WatchJettonsReturnType => { const { network, onChange } = options; diff --git a/packages/appkit/src/actions/network/get-api-client.ts b/packages/appkit/src/actions/network/get-api-client.ts index ff19b546e..1efde5465 100644 --- a/packages/appkit/src/actions/network/get-api-client.ts +++ b/packages/appkit/src/actions/network/get-api-client.ts @@ -10,12 +10,40 @@ import type { Network } from '../../types/network'; import type { AppKit } from '../../core/app-kit'; import type { ApiClient } from '../../core/network'; +/** + * Return type of {@link getApiClient}. + * + * @public + * @category Type + * @section Client + */ export type GetApiClientReturnType = ApiClient; -export type GetApiClientOptions = { network: Network }; +/** + * Options for {@link getApiClient}. + * + * @public + * @category Type + * @section Client + */ +export type GetApiClientOptions = { + /** Network whose configured {@link ApiClient} should be returned. */ + network: Network; +}; /** - * Get API client for a network + * Read the {@link ApiClient} configured for a specific {@link Network} — throws when the network has no client registered. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetApiClientOptions} Network to look up. + * @returns The configured {@link ApiClient} for the requested network. + * + * @sample docs/examples/src/appkit/actions/network#GET_API_CLIENT + * @expand options + * + * @public + * @category Action + * @section Client */ export const getApiClient = (appKit: AppKit, options: GetApiClientOptions): GetApiClientReturnType => { return appKit.networkManager.getClient(options.network); diff --git a/packages/appkit/src/actions/network/get-block-number.ts b/packages/appkit/src/actions/network/get-block-number.ts index 3cad4201c..9e94e687d 100644 --- a/packages/appkit/src/actions/network/get-block-number.ts +++ b/packages/appkit/src/actions/network/get-block-number.ts @@ -6,18 +6,43 @@ * */ -import { Network } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import { Network } from '../../types/network'; +/** + * Options for {@link getBlockNumber}. + * + * @public + * @category Type + * @section Networks + */ export interface GetBlockNumberOptions { + /** Network to query. Defaults to mainnet when omitted. */ network?: Network; } +/** + * Return type of {@link getBlockNumber}. + * + * @public + * @category Type + * @section Networks + */ export type GetBlockNumberReturnType = number; /** - * Get the latest block number (seqno) of the masterchain for the specified network (or mainnet by default). + * Read the latest masterchain seqno (block number) for a network — useful for pagination cursors and freshness checks. Defaults to mainnet when no network is given. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetBlockNumberOptions} Optional network override. + * @returns Current masterchain seqno as a number. + * + * @sample docs/examples/src/appkit/actions/network#GET_BLOCK_NUMBER + * @expand options + * + * @public + * @category Action + * @section Networks */ export const getBlockNumber = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/network/get-default-network.ts b/packages/appkit/src/actions/network/get-default-network.ts index 527e97659..682e528ad 100644 --- a/packages/appkit/src/actions/network/get-default-network.ts +++ b/packages/appkit/src/actions/network/get-default-network.ts @@ -9,10 +9,26 @@ import type { Network } from '../../types/network'; import type { AppKit } from '../../core/app-kit'; +/** + * Return type of {@link getDefaultNetwork} — `undefined` when no default has been set (apps may operate on any registered network). + * + * @public + * @category Type + * @section Networks + */ export type GetDefaultNetworkReturnType = Network | undefined; /** - * Get the current default network + * Read AppKit's currently configured default network — the one connectors enforce on new wallet connections. `undefined` means any registered network is allowed. + * + * @param appKit - {@link AppKit} Runtime instance. + * @returns The default {@link Network}, or `undefined` if none is set. + * + * @sample docs/examples/src/appkit/actions/network#GET_DEFAULT_NETWORK + * + * @public + * @category Action + * @section Networks */ export const getDefaultNetwork = (appKit: AppKit): GetDefaultNetworkReturnType => { return appKit.networkManager.getDefaultNetwork(); diff --git a/packages/appkit/src/actions/network/get-network.ts b/packages/appkit/src/actions/network/get-network.ts index 3a47c4501..f965f24bf 100644 --- a/packages/appkit/src/actions/network/get-network.ts +++ b/packages/appkit/src/actions/network/get-network.ts @@ -10,10 +10,26 @@ import type { Network } from '../../types/network'; import type { AppKit } from '../../core/app-kit'; import { getSelectedWallet } from '../wallets/get-selected-wallet'; +/** + * Return type of {@link getNetwork} — `null` when no wallet is currently selected. + * + * @public + * @category Type + * @section Networks + */ export type GetNetworkReturnType = Network | null; /** - * Get the network of the currently selected wallet + * Read the {@link Network} the selected wallet is connected to, or `null` when no wallet is selected (use {@link getDefaultNetwork} for AppKit's configured default). + * + * @param appKit - {@link AppKit} Runtime instance. + * @returns Network of the selected wallet, or `null` when none is selected. + * + * @sample docs/examples/src/appkit/actions/network#GET_NETWORK + * + * @public + * @category Action + * @section Networks */ export const getNetwork = (appKit: AppKit): GetNetworkReturnType => { const wallet = getSelectedWallet(appKit); diff --git a/packages/appkit/src/actions/network/get-networks.ts b/packages/appkit/src/actions/network/get-networks.ts index 646e0f7df..e9251bb1b 100644 --- a/packages/appkit/src/actions/network/get-networks.ts +++ b/packages/appkit/src/actions/network/get-networks.ts @@ -9,10 +9,26 @@ import type { Network } from '../../types/network'; import type { AppKit } from '../../core/app-kit'; +/** + * Return type of {@link getNetworks}. + * + * @public + * @category Type + * @section Networks + */ export type GetNetworksReturnType = Network[]; /** - * Get all configured networks + * List every network configured on this AppKit instance via {@link AppKitConfig}'s `networks`. + * + * @param appKit - {@link AppKit} Runtime instance. + * @returns Array of configured {@link Network}s. + * + * @sample docs/examples/src/appkit/actions/network#GET_NETWORKS + * + * @public + * @category Action + * @section Networks */ export const getNetworks = (appKit: AppKit): GetNetworksReturnType => { return appKit.networkManager.getConfiguredNetworks(); diff --git a/packages/appkit/src/actions/network/has-streaming-provider.ts b/packages/appkit/src/actions/network/has-streaming-provider.ts index 2144996cf..18e90831a 100644 --- a/packages/appkit/src/actions/network/has-streaming-provider.ts +++ b/packages/appkit/src/actions/network/has-streaming-provider.ts @@ -9,10 +9,27 @@ import type { AppKit } from '../../core/app-kit/services/app-kit'; import type { Network } from '../../types/network'; +/** + * Return type of {@link hasStreamingProvider}. + * + * @public + * @category Type + * @section Networks + */ export type HasStreamingProviderReturnType = boolean; /** - * Check if a streaming provider is registered for a specific network. + * Check whether a streaming provider is registered for a network — required by {@link watchBalance}, {@link watchJettons} and other live-update actions. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param network - {@link Network} Network to check. + * @returns `true` when a streaming provider is registered for that network. + * + * @sample docs/examples/src/appkit/actions/network#HAS_STREAMING_PROVIDER + * + * @public + * @category Action + * @section Networks */ export const hasStreamingProvider = (appKit: AppKit, network: Network): HasStreamingProviderReturnType => { return appKit.streamingManager.hasProvider(network); diff --git a/packages/appkit/src/actions/network/set-default-network.ts b/packages/appkit/src/actions/network/set-default-network.ts index d46a4be63..9640b7a1f 100644 --- a/packages/appkit/src/actions/network/set-default-network.ts +++ b/packages/appkit/src/actions/network/set-default-network.ts @@ -9,16 +9,39 @@ import type { Network } from '../../types/network'; import type { AppKit } from '../../core/app-kit'; +/** + * Parameters accepted by {@link setDefaultNetwork}. + * + * @public + * @category Type + * @section Networks + */ export type SetDefaultNetworkParameters = { + /** Network to enforce on new wallet connections. Pass `undefined` to allow any registered network. */ network: Network | undefined; }; +/** + * Return type of {@link setDefaultNetwork}. + * + * @public + * @category Type + * @section Networks + */ export type SetDefaultNetworkReturnType = void; /** - * Set the default network for wallet connections. - * If set, connectors will enforce this network when connecting. - * Set to `undefined` to allow any network. + * Set or clear the default network — connectors enforce it on new wallet connections. Emits `NETWORKS_EVENTS.DEFAULT_CHANGED` so {@link watchDefaultNetwork} subscribers fire. Pass `undefined` to remove the constraint and allow any registered network. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link SetDefaultNetworkParameters} Network to enforce, or `undefined` to clear. + * + * @sample docs/examples/src/appkit/actions/network#SET_DEFAULT_NETWORK + * @expand parameters + * + * @public + * @category Action + * @section Networks */ export const setDefaultNetwork = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/network/watch-default-network.ts b/packages/appkit/src/actions/network/watch-default-network.ts index 1365f3dd6..f7c66d77c 100644 --- a/packages/appkit/src/actions/network/watch-default-network.ts +++ b/packages/appkit/src/actions/network/watch-default-network.ts @@ -11,14 +11,40 @@ import type { AppKit } from '../../core/app-kit'; import { getDefaultNetwork } from './get-default-network'; import { NETWORKS_EVENTS } from '../../core/app-kit'; +/** + * Parameters accepted by {@link watchDefaultNetwork}. + * + * @public + * @category Type + * @section Networks + */ export type WatchDefaultNetworkParameters = { + /** Callback fired whenever {@link setDefaultNetwork} updates the default — receives the new value (or `undefined` when cleared). */ onChange: (network: Network | undefined) => void; }; +/** + * Return type of {@link watchDefaultNetwork} — call to stop receiving updates. + * + * @public + * @category Type + * @section Networks + */ export type WatchDefaultNetworkReturnType = () => void; /** - * Watch default network changes + * Subscribe to default-network changes — fires when {@link setDefaultNetwork} is called. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link WatchDefaultNetworkParameters} Update callback. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @sample docs/examples/src/appkit/actions/network#WATCH_DEFAULT_NETWORK + * @expand parameters + * + * @public + * @category Action + * @section Networks */ export const watchDefaultNetwork = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/network/watch-networks.ts b/packages/appkit/src/actions/network/watch-networks.ts index 0c3562d50..19d2c2158 100644 --- a/packages/appkit/src/actions/network/watch-networks.ts +++ b/packages/appkit/src/actions/network/watch-networks.ts @@ -11,14 +11,40 @@ import { getNetworks } from './get-networks'; import type { AppKit } from '../../core/app-kit'; import { NETWORKS_EVENTS } from '../../core/app-kit'; +/** + * Parameters accepted by {@link watchNetworks}. + * + * @public + * @category Type + * @section Networks + */ export type WatchNetworksParameters = { + /** Callback fired whenever the configured-networks list changes — receives the latest snapshot. */ onChange: (networks: Network[]) => void; }; +/** + * Return type of {@link watchNetworks} — call to stop receiving updates. + * + * @public + * @category Type + * @section Networks + */ export type WatchNetworksReturnType = () => void; /** - * Watch configured networks + * Subscribe to changes of the configured-networks list — fires when AppKit's network manager registers or replaces a network's API client. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link WatchNetworksParameters} Update callback. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @sample docs/examples/src/appkit/actions/network#WATCH_NETWORKS + * @expand parameters + * + * @public + * @category Action + * @section Networks */ export const watchNetworks = (appKit: AppKit, parameters: WatchNetworksParameters): WatchNetworksReturnType => { const { onChange } = parameters; diff --git a/packages/appkit/src/actions/nft/create-transfer-nft-transaction.ts b/packages/appkit/src/actions/nft/create-transfer-nft-transaction.ts index 15f5c4a68..5e38e3015 100644 --- a/packages/appkit/src/actions/nft/create-transfer-nft-transaction.ts +++ b/packages/appkit/src/actions/nft/create-transfer-nft-transaction.ts @@ -6,23 +6,52 @@ * */ -import { createNftTransferPayload, createTransferTransaction, DEFAULT_NFT_GAS_FEE } from '@ton/walletkit'; - -import type { TransactionRequest } from '../../types/transaction'; import type { AppKit } from '../../core/app-kit'; +import type { TransactionRequest } from '../../types/transaction'; +import type { UserFriendlyAddress } from '../../types/primitives'; +import { createNftTransferPayload, createTransferTransaction, DEFAULT_NFT_GAS_FEE } from '../../utils'; import { getSelectedWallet } from '../wallets/get-selected-wallet'; +/** + * Parameters accepted by {@link createTransferNftTransaction} and {@link transferNft}. + * + * @public + * @category Type + * @section NFTs + */ export interface CreateTransferNftTransactionParameters { - nftAddress: string; - recipientAddress: string; + /** NFT contract address to transfer. */ + nftAddress: UserFriendlyAddress; + /** New owner address. */ + recipientAddress: UserFriendlyAddress; + /** Amount of TON to attach to the transfer for gas. Defaults to AppKit's NFT gas-fee constant when omitted. */ amount?: string; + /** Optional human-readable comment attached to the transfer. */ comment?: string; } +/** + * Return type of {@link createTransferNftTransaction}. + * + * @public + * @category Type + * @section NFTs + */ export type CreateTransferNftTransactionReturnType = TransactionRequest; /** - * Create a NFT transfer transaction request + * Build an NFT transfer {@link TransactionRequest} for the selected wallet without sending it — useful when the UI needs to inspect or batch transactions before signing. Throws `Error('Wallet not connected')` if no wallet is currently selected. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link CreateTransferNftTransactionParameters} NFT, recipient, optional gas amount and comment. + * @returns Transaction request ready to pass to `sendTransaction`. + * + * @sample docs/examples/src/appkit/actions/nft#CREATE_TRANSFER_NFT_TRANSACTION + * @expand parameters + * + * @public + * @category Action + * @section NFTs */ export const createTransferNftTransaction = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/nft/get-nft.ts b/packages/appkit/src/actions/nft/get-nft.ts index 62b588a2c..f521ce290 100644 --- a/packages/appkit/src/actions/nft/get-nft.ts +++ b/packages/appkit/src/actions/nft/get-nft.ts @@ -7,20 +7,51 @@ */ import { Address } from '@ton/core'; -import { getNftFromClient } from '@ton/walletkit'; import type { AppKit } from '../../core/app-kit'; -import { resolveNetwork } from '../../utils/network/resolve-network'; import type { Network } from '../../types/network'; import type { NFT } from '../../types/nft'; +import type { UserFriendlyAddress } from '../../types/primitives'; +import { getNftFromClient } from '../../utils'; +import { resolveNetwork } from '../../utils/network/resolve-network'; +/** + * Options for {@link getNft}. + * + * @public + * @category Type + * @section NFTs + */ export interface GetNftOptions { - address: string | Address; + /** NFT contract address — pass a {@link UserFriendlyAddress} string or an `Address` instance from `@ton/core`. */ + address: UserFriendlyAddress | Address; + /** Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; } +/** + * Return type of {@link getNft} — `null` when the indexer has no record for that address. + * + * @public + * @category Type + * @section NFTs + */ export type GetNftReturnType = NFT | null; +/** + * Fetch metadata and ownership for a single NFT by its contract address. Returns `null` when the indexer has no record. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetNftOptions} NFT address and optional network override. + * @returns NFT data, or `null` if the indexer has no record. + * + * @sample docs/examples/src/appkit/actions/nft#GET_NFT + * @expand options + * + * @public + * @category Action + * @section NFTs + */ export const getNft = async (appKit: AppKit, options: GetNftOptions): Promise => { const { address, network } = options; const addressString = Address.isAddress(address) ? address.toString() : Address.parse(address).toString(); diff --git a/packages/appkit/src/actions/nft/get-nfts-by-address.ts b/packages/appkit/src/actions/nft/get-nfts-by-address.ts index 278f3b472..3e6840feb 100644 --- a/packages/appkit/src/actions/nft/get-nfts-by-address.ts +++ b/packages/appkit/src/actions/nft/get-nfts-by-address.ts @@ -7,22 +7,55 @@ */ import { Address } from '@ton/core'; -import type { NFTsResponse } from '@ton/walletkit'; -import { getNftsFromClient } from '@ton/walletkit'; import type { AppKit } from '../../core/app-kit'; -import { resolveNetwork } from '../../utils/network/resolve-network'; import type { Network } from '../../types/network'; +import type { NFTsResponse } from '../../types/nft'; +import type { UserFriendlyAddress } from '../../types/primitives'; +import { getNftsFromClient } from '../../utils'; +import { resolveNetwork } from '../../utils/network/resolve-network'; +/** + * Options for {@link getNftsByAddress}. + * + * @public + * @category Type + * @section NFTs + */ export interface GetNftsByAddressOptions { - address: string | Address; + /** Owner address — pass a {@link UserFriendlyAddress} string or an `Address` instance from `@ton/core`. */ + address: UserFriendlyAddress | Address; + /** Network to read NFTs from. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; + /** Maximum number of NFTs to return. */ limit?: number; + /** Number of NFTs to skip before returning results — used for pagination. */ offset?: number; } +/** + * Return type of {@link getNftsByAddress}. + * + * @public + * @category Type + * @section NFTs + */ export type GetNftsByAddressReturnType = NFTsResponse; +/** + * List NFTs held by an arbitrary address — useful for inspecting wallets that aren't selected in AppKit (use {@link getNfts} for the selected wallet). + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetNftsByAddressOptions} Owner address, optional network override and pagination. + * @returns NFTs response with the owner's items. + * + * @sample docs/examples/src/appkit/actions/nft#GET_NFTS_BY_ADDRESS + * @expand options + * + * @public + * @category Action + * @section NFTs + */ export const getNftsByAddress = async ( appKit: AppKit, options: GetNftsByAddressOptions, diff --git a/packages/appkit/src/actions/nft/get-nfts.ts b/packages/appkit/src/actions/nft/get-nfts.ts index f3e689864..369aaca84 100644 --- a/packages/appkit/src/actions/nft/get-nfts.ts +++ b/packages/appkit/src/actions/nft/get-nfts.ts @@ -6,21 +6,51 @@ * */ -import type { NFTsResponse } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; -import { getNftsByAddress } from './get-nfts-by-address'; -import { getSelectedWallet } from '../wallets/get-selected-wallet'; import type { Network } from '../../types/network'; +import type { NFTsResponse } from '../../types/nft'; +import { getSelectedWallet } from '../wallets/get-selected-wallet'; +import { getNftsByAddress } from './get-nfts-by-address'; +/** + * Options for {@link getNfts}. + * + * @public + * @category Type + * @section NFTs + */ export interface GetNftsOptions { + /** Network to read NFTs from. Defaults to the selected wallet's network. */ network?: Network; + /** Maximum number of NFTs to return. */ limit?: number; + /** Number of NFTs to skip before returning results — used for pagination. */ offset?: number; } +/** + * Return type of {@link getNfts} — `null` when no wallet is currently selected. + * + * @public + * @category Type + * @section NFTs + */ export type GetNftsReturnType = NFTsResponse | null; +/** + * List NFTs held by the currently selected wallet, returning `null` when no wallet is selected (use {@link getNftsByAddress} for an arbitrary address). + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetNftsOptions} Optional network override and pagination. + * @returns NFTs response for the selected wallet, or `null` when none is selected. + * + * @sample docs/examples/src/appkit/actions/nft#GET_NFTS + * @expand options + * + * @public + * @category Action + * @section NFTs + */ export const getNfts = async (appKit: AppKit, options: GetNftsOptions = {}): Promise => { const selectedWallet = getSelectedWallet(appKit); diff --git a/packages/appkit/src/actions/nft/transfer-nft.ts b/packages/appkit/src/actions/nft/transfer-nft.ts index 5fc71e5f4..b394a5bfc 100644 --- a/packages/appkit/src/actions/nft/transfer-nft.ts +++ b/packages/appkit/src/actions/nft/transfer-nft.ts @@ -6,19 +6,43 @@ * */ -import type { SendTransactionResponse } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { SendTransactionResponse } from '../../types/transaction'; +import { sendTransaction } from '../transaction/send-transaction'; import { createTransferNftTransaction } from './create-transfer-nft-transaction'; import type { CreateTransferNftTransactionParameters } from './create-transfer-nft-transaction'; -import { sendTransaction } from '../transaction/send-transaction'; +/** + * Parameters accepted by {@link transferNft} — same shape as {@link CreateTransferNftTransactionParameters}. + * + * @public + * @category Type + * @section NFTs + */ export type TransferNftParameters = CreateTransferNftTransactionParameters; +/** + * Return type of {@link transferNft}. + * + * @public + * @category Type + * @section NFTs + */ export type TransferNftReturnType = SendTransactionResponse; /** - * Transfer NFT to another wallet + * Build and send an NFT transfer from the selected wallet in one step (use {@link createTransferNftTransaction} + {@link sendTransaction} if you need to inspect the transaction first). Throws `Error('Wallet not connected')` if no wallet is currently selected. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link TransferNftParameters} NFT, recipient, optional gas amount and comment. + * @returns Wallet response carrying the BoC of the sent transaction. + * + * @sample docs/examples/src/appkit/actions/nft#TRANSFER_NFT + * @expand parameters + * + * @public + * @category Action + * @section NFTs */ export const transferNft = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/onramp/build-onramp-url.ts b/packages/appkit/src/actions/onramp/build-onramp-url.ts index ec4afbd4d..e81943f8c 100644 --- a/packages/appkit/src/actions/onramp/build-onramp-url.ts +++ b/packages/appkit/src/actions/onramp/build-onramp-url.ts @@ -6,9 +6,8 @@ * */ -import type { OnrampParams } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { OnrampParams } from '../../onramp'; export type BuildOnrampUrlOptions = OnrampParams & { providerId?: string; @@ -17,7 +16,7 @@ export type BuildOnrampUrlOptions = OnrampParams & { export type BuildOnrampUrlReturnType = Promise; /** - * Build onramp URL + * Build onramp URL. */ export const buildOnrampUrl = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/onramp/get-onramp-manager.ts b/packages/appkit/src/actions/onramp/get-onramp-manager.ts index 2fafad61b..3adcf068d 100644 --- a/packages/appkit/src/actions/onramp/get-onramp-manager.ts +++ b/packages/appkit/src/actions/onramp/get-onramp-manager.ts @@ -6,14 +6,13 @@ * */ -import type { OnrampManager } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { OnrampManager } from '../../onramp'; export type GetOnrampManagerReturnType = OnrampManager; /** - * Get onramp manager instance + * Get onramp manager instance. */ export const getOnrampManager = (appKit: AppKit): GetOnrampManagerReturnType => { return appKit.onrampManager; diff --git a/packages/appkit/src/actions/onramp/get-onramp-provider.ts b/packages/appkit/src/actions/onramp/get-onramp-provider.ts index 948386573..f08547c35 100644 --- a/packages/appkit/src/actions/onramp/get-onramp-provider.ts +++ b/packages/appkit/src/actions/onramp/get-onramp-provider.ts @@ -6,9 +6,8 @@ * */ -import type { OnrampProviderInterface } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { OnrampProviderInterface } from '../../onramp'; export interface GetOnrampProviderOptions { id?: string; @@ -17,7 +16,7 @@ export interface GetOnrampProviderOptions { export type GetOnrampProviderReturnType = OnrampProviderInterface; /** - * Get onramp provider + * Get onramp provider. */ export const getOnrampProvider = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/onramp/get-onramp-providers.ts b/packages/appkit/src/actions/onramp/get-onramp-providers.ts index 97440fc28..970d8867e 100644 --- a/packages/appkit/src/actions/onramp/get-onramp-providers.ts +++ b/packages/appkit/src/actions/onramp/get-onramp-providers.ts @@ -6,14 +6,13 @@ * */ -import type { OnrampProviderInterface } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { OnrampProviderInterface } from '../../onramp'; export type GetOnrampProvidersReturnType = OnrampProviderInterface[]; /** - * Get all registered onramp providers + * Get all registered onramp providers. */ export const getOnrampProviders = (appKit: AppKit): GetOnrampProvidersReturnType => { return appKit.onrampManager.getProviders(); diff --git a/packages/appkit/src/actions/onramp/get-onramp-quote.ts b/packages/appkit/src/actions/onramp/get-onramp-quote.ts index 7a6b46908..ffe8f1d13 100644 --- a/packages/appkit/src/actions/onramp/get-onramp-quote.ts +++ b/packages/appkit/src/actions/onramp/get-onramp-quote.ts @@ -6,10 +6,9 @@ * */ -import type { OnrampQuote, OnrampQuoteParams } from '@ton/walletkit'; - -import { resolveNetwork } from '../../utils'; import type { AppKit } from '../../core/app-kit'; +import type { OnrampQuote, OnrampQuoteParams } from '../../onramp'; +import { resolveNetwork } from '../../utils'; export type GetOnrampQuoteOptions = OnrampQuoteParams & { providerId?: string; @@ -18,7 +17,7 @@ export type GetOnrampQuoteOptions = OnrampQuoteParams & { export type GetOnrampQuoteReturnType = Promise; /** - * Get onramp quote + * Get onramp quote. */ export const getOnrampQuote = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/onramp/watch-onramp-providers.ts b/packages/appkit/src/actions/onramp/watch-onramp-providers.ts index a14d12682..ac0fef00b 100644 --- a/packages/appkit/src/actions/onramp/watch-onramp-providers.ts +++ b/packages/appkit/src/actions/onramp/watch-onramp-providers.ts @@ -15,7 +15,7 @@ export interface WatchOnrampProvidersParameters { export type WatchOnrampProvidersReturnType = () => void; /** - * Watch for new onramp providers registration + * Subscribe to onramp provider lifecycle — fires `onChange` whenever a new provider is registered or the default onramp provider switches. */ export const watchOnrampProviders = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/providers/register-provider.ts b/packages/appkit/src/actions/providers/register-provider.ts index 341c9d333..b4328a477 100644 --- a/packages/appkit/src/actions/providers/register-provider.ts +++ b/packages/appkit/src/actions/providers/register-provider.ts @@ -6,14 +6,29 @@ * */ -import type { ProviderInput } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { ProviderInput } from '../../types/provider'; +/** + * Provider instance or factory accepted by {@link registerProvider} — same shape used in {@link AppKitConfig}'s `providers`. AppKit dispatches it to the right manager based on `provider.type` (`'swap'`, `'staking'`, `'onramp'`, `'crypto-onramp'`). + * + * @public + * @category Type + * @section DeFi + */ export type RegisterProviderOptions = ProviderInput; /** - * Register provider + * Register a DeFi / onramp provider at runtime — equivalent to passing it via {@link AppKitConfig}'s `providers` at construction, but available after AppKit is up. AppKit emits `provider:registered`, picked up by domain-specific subscribers like {@link watchSwapProviders} and {@link watchCryptoOnrampProviders}. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param provider - {@link RegisterProviderOptions} Provider instance or factory to register. + * + * @sample docs/examples/src/appkit/actions/providers#REGISTER_PROVIDER + * + * @public + * @category Action + * @section DeFi */ export const registerProvider = (appKit: AppKit, provider: RegisterProviderOptions): void => { appKit.registerProvider(provider); diff --git a/packages/appkit/src/actions/signing/sign-binary.ts b/packages/appkit/src/actions/signing/sign-binary.ts index 8618e84bc..fa2670445 100644 --- a/packages/appkit/src/actions/signing/sign-binary.ts +++ b/packages/appkit/src/actions/signing/sign-binary.ts @@ -13,23 +13,42 @@ import { getSelectedWallet } from '../wallets/get-selected-wallet'; import type { Base64String } from '../../types/primitives'; import { getDefaultNetwork } from '../network/get-default-network'; +/** + * Parameters accepted by {@link signBinary}. + * + * @public + * @category Type + * @section Signing + */ export interface SignBinaryParameters { - /** Binary data to sign (base64 encoded) */ + /** Binary blob the user is asked to sign, encoded as Base64. */ bytes: Base64String; - /** Optional network (mainnet/testnet) */ + /** Network to issue the sign request against. Defaults to AppKit's configured default network. When none is set, the wallet falls back to its current network. */ network?: Network; } +/** + * Return type of {@link signBinary}. + * + * @public + * @category Type + * @section Signing + */ export type SignBinaryReturnType = SignDataResponse; /** - * Sign binary data with the connected wallet. + * Ask the selected wallet to sign a binary blob. Throws `Error('Wallet not connected')` if no wallet is currently selected. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link SignBinaryParameters} Binary content and optional network override. + * @returns Signature and signed payload, as returned by the wallet. + * + * @sample docs/examples/src/appkit/actions/signing#SIGN_BINARY + * @expand parameters * - * @example - * ```ts - * const result = await signBinary(appKit, { bytes: btoa("binary data") }); - * console.log(result.signature); - * ``` + * @public + * @category Action + * @section Signing */ export const signBinary = async (appKit: AppKit, parameters: SignBinaryParameters): Promise => { const wallet = getSelectedWallet(appKit); diff --git a/packages/appkit/src/actions/signing/sign-cell.ts b/packages/appkit/src/actions/signing/sign-cell.ts index ac3d833cc..a6377a469 100644 --- a/packages/appkit/src/actions/signing/sign-cell.ts +++ b/packages/appkit/src/actions/signing/sign-cell.ts @@ -13,29 +13,44 @@ import { getSelectedWallet } from '../wallets/get-selected-wallet'; import type { Base64String } from '../../types/primitives'; import { getDefaultNetwork } from '../network/get-default-network'; +/** + * Parameters accepted by {@link signCell}. + * + * @public + * @category Type + * @section Signing + */ export interface SignCellParameters { - /** Base64 encoded Bag of Cells */ + /** TON cell content encoded as Base64 (BoC). */ cell: Base64String; - /** TL-B schema for the cell structure */ + /** TL-B-style schema describing the cell layout so the wallet can render the payload to the user. */ schema: string; - /** Optional network (mainnet/testnet) */ + /** Network to issue the sign request against. Defaults to AppKit's configured default network. When none is set, the wallet falls back to its current network. */ network?: Network; } +/** + * Return type of {@link signCell}. + * + * @public + * @category Type + * @section Signing + */ export type SignCellReturnType = SignDataResponse; /** - * Sign a TON Cell with the connected wallet. - * Used for on-chain signature verification. + * Ask the selected wallet to sign a TON cell — typically used so the signature can later be verified on-chain. Throws `Error('Wallet not connected')` if no wallet is currently selected. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link SignCellParameters} Cell content, TL-B schema and optional network override. + * @returns Signature and signed payload, as returned by the wallet. + * + * @sample docs/examples/src/appkit/actions/signing#SIGN_CELL + * @expand parameters * - * @example - * ```ts - * const result = await signCell(appKit, { - * cell: bocBase64, - * schema: "transfer#abc123 amount:uint64 = Transfer" - * }); - * console.log(result.signature); - * ``` + * @public + * @category Action + * @section Signing */ export const signCell = async (appKit: AppKit, parameters: SignCellParameters): Promise => { const wallet = getSelectedWallet(appKit); diff --git a/packages/appkit/src/actions/signing/sign-text.ts b/packages/appkit/src/actions/signing/sign-text.ts index d9fbb621b..f52b202c5 100644 --- a/packages/appkit/src/actions/signing/sign-text.ts +++ b/packages/appkit/src/actions/signing/sign-text.ts @@ -12,23 +12,42 @@ import type { SignDataResponse } from '../../types/signing'; import { getSelectedWallet } from '../wallets/get-selected-wallet'; import { getDefaultNetwork } from '../network/get-default-network'; +/** + * Parameters accepted by {@link signText}. + * + * @public + * @category Type + * @section Signing + */ export interface SignTextParameters { - /** Text message to sign */ + /** UTF-8 text the user is asked to sign. */ text: string; - /** Optional network (mainnet/testnet) */ + /** Network to issue the sign request against. Defaults to AppKit's configured default network. When none is set, the wallet falls back to its current network. */ network?: Network; } +/** + * Return type of {@link signText}. + * + * @public + * @category Type + * @section Signing + */ export type SignTextReturnType = SignDataResponse; /** - * Sign a text message with the connected wallet. + * Ask the selected wallet to sign a plain text message. Throws `Error('Wallet not connected')` if no wallet is currently selected. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link SignTextParameters} Text to sign and optional network override. + * @returns Signature and signed payload, as returned by the wallet. + * + * @sample docs/examples/src/appkit/actions/signing#SIGN_TEXT + * @expand parameters * - * @example - * ```ts - * const result = await signText(appKit, { text: "Hello World" }); - * console.log(result.signature); - * ``` + * @public + * @category Action + * @section Signing */ export const signText = async (appKit: AppKit, parameters: SignTextParameters): Promise => { const wallet = getSelectedWallet(appKit); diff --git a/packages/appkit/src/actions/staking/build-stake-transaction.ts b/packages/appkit/src/actions/staking/build-stake-transaction.ts index 6cadb0f48..264d150ac 100644 --- a/packages/appkit/src/actions/staking/build-stake-transaction.ts +++ b/packages/appkit/src/actions/staking/build-stake-transaction.ts @@ -6,19 +6,44 @@ * */ -import type { StakeParams } from '@ton/walletkit'; - -import type { TransactionRequest } from '../../types/transaction'; import type { AppKit } from '../../core/app-kit'; +import type { StakeParams } from '../../staking'; +import type { TransactionRequest } from '../../types/transaction'; +/** + * Options for {@link buildStakeTransaction} — extends {@link StakeParams} with an optional provider override. + * + * @public + * @category Type + * @section Staking + */ export type BuildStakeTransactionOptions = StakeParams & { + /** Provider to stake/unstake through. Defaults to the registered default staking provider. */ providerId?: string; }; +/** + * Return type of {@link buildStakeTransaction}. + * + * @public + * @category Type + * @section Staking + */ export type BuildStakeTransactionReturnType = Promise; /** - * Build stake transaction + * Build a {@link TransactionRequest} that executes a stake or unstake previously quoted by {@link getStakingQuote} — returns it without sending so the UI can inspect or batch before signing. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link BuildStakeTransactionOptions} Quote and optional provider override. + * @returns Transaction request ready to pass to `sendTransaction`. + * + * @sample docs/examples/src/appkit/actions/staking#BUILD_STAKE_TRANSACTION + * @expand options + * + * @public + * @category Action + * @section Staking */ export const buildStakeTransaction = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/staking/get-staked-balance.ts b/packages/appkit/src/actions/staking/get-staked-balance.ts index f975dc764..24c0935d8 100644 --- a/packages/appkit/src/actions/staking/get-staked-balance.ts +++ b/packages/appkit/src/actions/staking/get-staked-balance.ts @@ -6,21 +6,50 @@ * */ -import type { StakingBalance, UserFriendlyAddress, Network } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { StakingBalance } from '../../staking'; +import type { Network } from '../../types/network'; +import type { UserFriendlyAddress } from '../../types/primitives'; import { resolveNetwork } from '../../utils'; +/** + * Options for {@link getStakedBalance}. + * + * @public + * @category Type + * @section Staking + */ export type GetStakedBalanceOptions = { + /** Owner whose staked balance should be read. */ userAddress: UserFriendlyAddress; + /** Network to query. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; + /** Provider to query. Defaults to the registered default staking provider. */ providerId?: string; }; +/** + * Return type of {@link getStakedBalance}. + * + * @public + * @category Type + * @section Staking + */ export type GetStakedBalanceReturnType = Promise; /** - * Get staked balance + * Read a user's staked balance from a staking provider — total staked plus, depending on the provider, any instant-unstake balance available right now. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetStakedBalanceOptions} Owner address and optional network/provider override. + * @returns Staked-balance breakdown ({@link StakingBalance}) for the user on the resolved network/provider. + * + * @sample docs/examples/src/appkit/actions/staking#GET_STAKED_BALANCE + * @expand options + * + * @public + * @category Action + * @section Staking */ export const getStakedBalance = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/staking/get-staking-manager.ts b/packages/appkit/src/actions/staking/get-staking-manager.ts index d5243498f..e23c0ca96 100644 --- a/packages/appkit/src/actions/staking/get-staking-manager.ts +++ b/packages/appkit/src/actions/staking/get-staking-manager.ts @@ -6,14 +6,27 @@ * */ -import type { StakingManager } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { StakingManager } from '../../staking'; +/** + * Return type of {@link getStakingManager}. + * + * @public + * @category Type + * @section Staking + */ export type GetStakingManagerReturnType = StakingManager; /** - * Get staking manager instance + * Read AppKit's {@link StakingManager} — the runtime that owns registered staking providers and dispatches quote/stake/balance calls. Apps usually use the higher-level actions ({@link getStakingQuote}, {@link buildStakeTransaction}, {@link getStakedBalance}) instead of touching the manager directly. + * + * @param appKit - {@link AppKit} Runtime instance. + * @returns The {@link StakingManager} bound to this AppKit instance. + * + * @public + * @category Action + * @section Staking */ export const getStakingManager = (appKit: AppKit): GetStakingManagerReturnType => { return appKit.stakingManager; diff --git a/packages/appkit/src/actions/staking/get-staking-provider-info.ts b/packages/appkit/src/actions/staking/get-staking-provider-info.ts index eab2a1b7b..ec27a79f8 100644 --- a/packages/appkit/src/actions/staking/get-staking-provider-info.ts +++ b/packages/appkit/src/actions/staking/get-staking-provider-info.ts @@ -6,20 +6,47 @@ * */ -import type { StakingProviderInfo, Network } from '@ton/walletkit'; - -import { resolveNetwork } from '../../utils'; import type { AppKit } from '../../core/app-kit'; +import type { StakingProviderInfo } from '../../staking'; +import type { Network } from '../../types/network'; +import { resolveNetwork } from '../../utils'; +/** + * Options for {@link getStakingProviderInfo}. + * + * @public + * @category Type + * @section Staking + */ export type GetStakingProviderInfoOptions = { + /** Network whose staking pool should be inspected. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; + /** Provider to query. Defaults to the registered default staking provider. */ providerId?: string; }; +/** + * Return type of {@link getStakingProviderInfo}. + * + * @public + * @category Type + * @section Staking + */ export type GetStakingProviderInfoReturnType = Promise; /** - * Get staking provider info + * Read live staking-pool info for a provider — APY, instant-unstake liquidity and (for liquid staking) the current exchange rate between stake and receive tokens. Use {@link getStakingProviderMetadata} for static metadata (display name, stake/receive tokens, supported unstake modes). + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetStakingProviderInfoOptions} Optional network and provider override. + * @returns Live staking-provider info for the resolved network. + * + * @sample docs/examples/src/appkit/actions/staking#GET_STAKING_PROVIDER_INFO + * @expand options + * + * @public + * @category Action + * @section Staking */ export const getStakingProviderInfo = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/staking/get-staking-provider-metadata.ts b/packages/appkit/src/actions/staking/get-staking-provider-metadata.ts index 6c709ead1..cfe7d33fe 100644 --- a/packages/appkit/src/actions/staking/get-staking-provider-metadata.ts +++ b/packages/appkit/src/actions/staking/get-staking-provider-metadata.ts @@ -6,20 +6,47 @@ * */ -import type { StakingProviderMetadata, Network } from '@ton/walletkit'; - -import { resolveNetwork } from '../../utils'; import type { AppKit } from '../../core/app-kit'; +import type { StakingProviderMetadata } from '../../staking'; +import type { Network } from '../../types/network'; +import { resolveNetwork } from '../../utils'; +/** + * Options for {@link getStakingProviderMetadata}. + * + * @public + * @category Type + * @section Staking + */ export type GetStakingProviderMetadataOptions = { + /** Network whose provider metadata should be read. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; + /** Provider to query. Defaults to the registered default staking provider. */ providerId?: string; }; +/** + * Return type of {@link getStakingProviderMetadata}. + * + * @public + * @category Type + * @section Staking + */ export type GetStakingProviderMetadataReturnType = StakingProviderMetadata; /** - * Get staking provider static metadata + * Read static metadata for a staking provider — display name, stake/receive tokens, supported unstake modes, contract address. Use {@link getStakingProviderInfo} for live values (APY, instant-unstake liquidity, exchange rate). + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetStakingProviderMetadataOptions} Optional network and provider override. + * @returns Static {@link StakingProviderMetadata} for the resolved provider. + * + * @sample docs/examples/src/appkit/actions/staking#GET_STAKING_PROVIDER_METADATA + * @expand options + * + * @public + * @category Action + * @section Staking */ export const getStakingProviderMetadata = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/staking/get-staking-provider.ts b/packages/appkit/src/actions/staking/get-staking-provider.ts index 3b7c168b6..2a9150ab8 100644 --- a/packages/appkit/src/actions/staking/get-staking-provider.ts +++ b/packages/appkit/src/actions/staking/get-staking-provider.ts @@ -6,21 +6,42 @@ * */ -import type { StakingProviderInterface } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { StakingProviderInterface } from '../../staking'; +/** + * Options for {@link getStakingProvider}. + * + * @public + * @category Type + * @section Staking + */ export type GetStakingProviderOptions = { - /** - * Provider ID to get. If not provided, returns default provider. - */ + /** Provider ID to look up. When omitted, returns the registered default staking provider. */ id?: string; }; +/** + * Return type of {@link getStakingProvider}. + * + * @public + * @category Type + * @section Staking + */ export type GetStakingProviderReturnType = StakingProviderInterface; /** - * Get staking provider instance + * Get a registered staking provider by id, or the default staking provider when no id is given. Throws when no provider matches — or when no id is passed and no default has been registered. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetStakingProviderOptions} Optional provider id. + * @returns The matching staking provider instance. + * + * @expand options + * + * @public + * @category Action + * @section Staking */ export const getStakingProvider = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/staking/get-staking-providers.ts b/packages/appkit/src/actions/staking/get-staking-providers.ts index 2d0c4dbc4..33683a491 100644 --- a/packages/appkit/src/actions/staking/get-staking-providers.ts +++ b/packages/appkit/src/actions/staking/get-staking-providers.ts @@ -6,14 +6,29 @@ * */ -import type { StakingProviderInterface } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { StakingProviderInterface } from '../../staking'; +/** + * Return type of {@link getStakingProviders}. + * + * @public + * @category Type + * @section Staking + */ export type GetStakingProvidersReturnType = StakingProviderInterface[]; /** - * Get all registered staking providers. + * List every staking provider registered on this AppKit instance — both those passed via {@link AppKitConfig}'s `providers` and those added later through {@link registerProvider}. + * + * @param appKit - {@link AppKit} Runtime instance. + * @returns Array of registered staking providers. + * + * @sample docs/examples/src/appkit/actions/staking#GET_STAKING_PROVIDERS + * + * @public + * @category Action + * @section Staking */ export const getStakingProviders = (appKit: AppKit): GetStakingProvidersReturnType => { return appKit.stakingManager.getProviders(); diff --git a/packages/appkit/src/actions/staking/get-staking-quote.ts b/packages/appkit/src/actions/staking/get-staking-quote.ts index fa683764e..1d1b32213 100644 --- a/packages/appkit/src/actions/staking/get-staking-quote.ts +++ b/packages/appkit/src/actions/staking/get-staking-quote.ts @@ -6,19 +6,44 @@ * */ -import type { StakingQuote, StakingQuoteParams } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { StakingQuote, StakingQuoteParams } from '../../staking'; import { resolveNetwork } from '../../utils'; +/** + * Options for {@link getStakingQuote} — extends {@link StakingQuoteParams} with an optional provider override. + * + * @public + * @category Type + * @section Staking + */ export type GetStakingQuoteOptions = StakingQuoteParams & { + /** Provider to quote against. Defaults to the registered default staking provider. */ providerId?: string; }; +/** + * Return type of {@link getStakingQuote}. + * + * @public + * @category Type + * @section Staking + */ export type GetStakingQuoteReturnType = Promise; /** - * Get staking quote + * Quote a stake or unstake — given the amount, direction and target asset, returns the rate, expected output and provider metadata needed to call {@link buildStakeTransaction}. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetStakingQuoteOptions} Quote parameters and optional provider override. + * @returns Quote with pricing details and provider metadata. + * + * @sample docs/examples/src/appkit/actions/staking#GET_STAKING_QUOTE + * @expand options + * + * @public + * @category Action + * @section Staking */ export const getStakingQuote = async (appKit: AppKit, options: GetStakingQuoteOptions): GetStakingQuoteReturnType => { const optionsWithNetwork = { diff --git a/packages/appkit/src/actions/staking/set-default-staking-provider.ts b/packages/appkit/src/actions/staking/set-default-staking-provider.ts index 58822fbb5..c02402c1e 100644 --- a/packages/appkit/src/actions/staking/set-default-staking-provider.ts +++ b/packages/appkit/src/actions/staking/set-default-staking-provider.ts @@ -8,15 +8,38 @@ import type { AppKit } from '../../core/app-kit'; +/** + * Parameters accepted by {@link setDefaultStakingProvider}. + * + * @public + * @category Type + * @section Staking + */ export interface SetDefaultStakingProviderParameters { + /** ID of the provider to make default — must already be registered. */ providerId: string; } +/** + * Return type of {@link setDefaultStakingProvider}. + * + * @public + * @category Type + * @section Staking + */ export type SetDefaultStakingProviderReturnType = void; /** - * Set the default staking provider. - * Subsequent quote and stake-transaction calls will use this provider when none is specified. + * Set the default staking provider — subsequent {@link getStakingQuote} and {@link buildStakeTransaction} calls without an explicit `providerId` route through it. Emits `provider:default-changed`, picked up by {@link watchStakingProviders}. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link SetDefaultStakingProviderParameters} ID of the provider to make default. + * + * @expand parameters + * + * @public + * @category Action + * @section Staking */ export const setDefaultStakingProvider = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/staking/watch-staking-providers.ts b/packages/appkit/src/actions/staking/watch-staking-providers.ts index 5497bf86e..56d6720be 100644 --- a/packages/appkit/src/actions/staking/watch-staking-providers.ts +++ b/packages/appkit/src/actions/staking/watch-staking-providers.ts @@ -8,14 +8,39 @@ import type { AppKit } from '../../core/app-kit'; +/** + * Parameters accepted by {@link watchStakingProviders}. + * + * @public + * @category Type + * @section Staking + */ export interface WatchStakingProvidersParameters { + /** Callback fired whenever a staking provider is registered or the default staking provider changes. */ onChange: () => void; } +/** + * Return type of {@link watchStakingProviders} — call to stop receiving updates. + * + * @public + * @category Type + * @section Staking + */ export type WatchStakingProvidersReturnType = () => void; /** - * Watch for staking providers registration and default provider changes + * Subscribe to staking provider lifecycle — fires `onChange` whenever a new provider is registered or the default staking provider switches. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link WatchStakingProvidersParameters} Update callback. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @expand parameters + * + * @public + * @category Action + * @section Staking */ export const watchStakingProviders = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/swap/build-swap-transaction.ts b/packages/appkit/src/actions/swap/build-swap-transaction.ts index 5408fb643..8a1c5cd7e 100644 --- a/packages/appkit/src/actions/swap/build-swap-transaction.ts +++ b/packages/appkit/src/actions/swap/build-swap-transaction.ts @@ -10,12 +10,37 @@ import type { SwapParams } from '../../swap'; import type { TransactionRequest } from '../../types/transaction'; import type { AppKit } from '../../core/app-kit'; +/** + * Options for {@link buildSwapTransaction} — same shape as {@link SwapParams}. + * + * @public + * @category Type + * @section Swap + */ export type BuildSwapTransactionOptions = SwapParams; +/** + * Return type of {@link buildSwapTransaction}. + * + * @public + * @category Type + * @section Swap + */ export type BuildSwapTransactionReturnType = Promise; /** - * Build swap transaction + * Build a {@link TransactionRequest} that executes a swap previously quoted by {@link getSwapQuote} — returns it without sending so the UI can inspect or batch before signing. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link BuildSwapTransactionOptions} Quote and provider-specific options. + * @returns Transaction request ready to pass to `sendTransaction`. + * + * @sample docs/examples/src/appkit/actions/swap#BUILD_SWAP_TRANSACTION + * @expand options + * + * @public + * @category Action + * @section Swap */ export const buildSwapTransaction = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/swap/get-swap-manager.ts b/packages/appkit/src/actions/swap/get-swap-manager.ts index 191a0e563..a44e85285 100644 --- a/packages/appkit/src/actions/swap/get-swap-manager.ts +++ b/packages/appkit/src/actions/swap/get-swap-manager.ts @@ -6,14 +6,29 @@ * */ -import type { SwapManager } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { SwapManager } from '../../swap'; +/** + * Return type of {@link getSwapManager}. + * + * @public + * @category Type + * @section Swap + */ export type GetSwapManagerReturnType = SwapManager; /** - * Get swap manager instance + * Read AppKit's {@link SwapManager} — the runtime that owns registered swap providers and dispatches quote/build calls. Apps usually use the higher-level actions ({@link getSwapQuote}, {@link buildSwapTransaction}) instead of touching the manager directly. + * + * @param appKit - {@link AppKit} Runtime instance. + * @returns The {@link SwapManager} bound to this AppKit instance. + * + * @sample docs/examples/src/appkit/actions/swap#GET_SWAP_MANAGER + * + * @public + * @category Action + * @section Swap */ export const getSwapManager = (appKit: AppKit): GetSwapManagerReturnType => { return appKit.swapManager; diff --git a/packages/appkit/src/actions/swap/get-swap-provider.ts b/packages/appkit/src/actions/swap/get-swap-provider.ts index d302927c0..28fab5643 100644 --- a/packages/appkit/src/actions/swap/get-swap-provider.ts +++ b/packages/appkit/src/actions/swap/get-swap-provider.ts @@ -6,16 +6,44 @@ * */ -import type { SwapProviderInterface } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { SwapProviderInterface } from '../../swap'; +/** + * Options for {@link getSwapProvider}. + * + * @public + * @category Type + * @section Swap + */ export interface GetSwapProviderOptions { + /** Provider ID to look up. When omitted, returns the registered default swap provider. */ id?: string; } +/** + * Return type of {@link getSwapProvider}. + * + * @public + * @category Type + * @section Swap + */ export type GetSwapProviderReturnType = SwapProviderInterface; +/** + * Get a registered swap provider by id, or the default swap provider when no id is given. Throws when no provider matches — or when no id is passed and no default has been registered. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetSwapProviderOptions} Optional provider id. + * @returns The matching swap provider instance. + * + * @sample docs/examples/src/appkit/actions/swap#GET_SWAP_PROVIDER + * @expand options + * + * @public + * @category Action + * @section Swap + */ export const getSwapProvider = (appKit: AppKit, options: GetSwapProviderOptions = {}): GetSwapProviderReturnType => { return appKit.swapManager.getProvider(options.id); }; diff --git a/packages/appkit/src/actions/swap/get-swap-providers.ts b/packages/appkit/src/actions/swap/get-swap-providers.ts index 04bafa021..5b3e54e0c 100644 --- a/packages/appkit/src/actions/swap/get-swap-providers.ts +++ b/packages/appkit/src/actions/swap/get-swap-providers.ts @@ -6,14 +6,29 @@ * */ -import type { SwapProviderInterface } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { SwapProviderInterface } from '../../swap'; +/** + * Return type of {@link getSwapProviders}. + * + * @public + * @category Type + * @section Swap + */ export type GetSwapProvidersReturnType = SwapProviderInterface[]; /** - * Get all registered swap providers. + * List every swap provider registered on this AppKit instance — both those passed via {@link AppKitConfig}'s `providers` and those added later through {@link registerProvider}. + * + * @param appKit - {@link AppKit} Runtime instance. + * @returns Array of registered swap providers. + * + * @sample docs/examples/src/appkit/actions/swap#GET_SWAP_PROVIDERS + * + * @public + * @category Action + * @section Swap */ export const getSwapProviders = (appKit: AppKit): GetSwapProvidersReturnType => { return appKit.swapManager.getProviders(); diff --git a/packages/appkit/src/actions/swap/get-swap-quote.ts b/packages/appkit/src/actions/swap/get-swap-quote.ts index 1d716a88b..6d7c8ade0 100644 --- a/packages/appkit/src/actions/swap/get-swap-quote.ts +++ b/packages/appkit/src/actions/swap/get-swap-quote.ts @@ -6,19 +6,44 @@ * */ -import type { SwapQuote, SwapQuoteParams } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { SwapQuote, SwapQuoteParams } from '../../swap'; import { resolveNetwork } from '../../utils'; +/** + * Options for {@link getSwapQuote} — extends {@link SwapQuoteParams} with an optional provider override. + * + * @public + * @category Type + * @section Swap + */ export type GetSwapQuoteOptions = SwapQuoteParams & { + /** Provider to quote against. Defaults to the registered default swap provider. */ providerId?: string; }; +/** + * Return type of {@link getSwapQuote}. + * + * @public + * @category Type + * @section Swap + */ export type GetSwapQuoteReturnType = Promise; /** - * Get swap quote + * Quote a swap — given source/target tokens and an amount, returns the rate, expected output and provider metadata needed to call {@link buildSwapTransaction}. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link GetSwapQuoteOptions} Source and target tokens, amount, optional network and provider override. + * @returns Quote with pricing details and the provider metadata required to build a transaction. + * + * @sample docs/examples/src/appkit/actions/swap#GET_SWAP_QUOTE + * @expand options + * + * @public + * @category Action + * @section Swap */ export const getSwapQuote = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/swap/set-default-swap-provider.ts b/packages/appkit/src/actions/swap/set-default-swap-provider.ts index 583f0078a..554a71abd 100644 --- a/packages/appkit/src/actions/swap/set-default-swap-provider.ts +++ b/packages/appkit/src/actions/swap/set-default-swap-provider.ts @@ -8,15 +8,39 @@ import type { AppKit } from '../../core/app-kit'; +/** + * Parameters accepted by {@link setDefaultSwapProvider}. + * + * @public + * @category Type + * @section Swap + */ export interface SetDefaultSwapProviderParameters { + /** ID of the provider to make default — must already be registered. */ providerId: string; } +/** + * Return type of {@link setDefaultSwapProvider}. + * + * @public + * @category Type + * @section Swap + */ export type SetDefaultSwapProviderReturnType = void; /** - * Set the default swap provider. - * Subsequent quote and swap-transaction calls will use this provider when none is specified. + * Set the default swap provider — subsequent {@link getSwapQuote} and {@link buildSwapTransaction} calls without an explicit `providerId` route through it. Emits `provider:default-changed`, picked up by {@link watchSwapProviders}. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link SetDefaultSwapProviderParameters} ID of the provider to make default. + * + * @sample docs/examples/src/appkit/actions/swap#SET_DEFAULT_SWAP_PROVIDER + * @expand parameters + * + * @public + * @category Action + * @section Swap */ export const setDefaultSwapProvider = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/swap/watch-swap-providers.ts b/packages/appkit/src/actions/swap/watch-swap-providers.ts index c29094be9..9d6237ea5 100644 --- a/packages/appkit/src/actions/swap/watch-swap-providers.ts +++ b/packages/appkit/src/actions/swap/watch-swap-providers.ts @@ -8,14 +8,40 @@ import type { AppKit } from '../../core/app-kit'; +/** + * Parameters accepted by {@link watchSwapProviders}. + * + * @public + * @category Type + * @section Swap + */ export interface WatchSwapProvidersParameters { + /** Callback fired whenever a swap provider is registered or the default swap provider changes. */ onChange: () => void; } +/** + * Return type of {@link watchSwapProviders} — call to stop receiving updates. + * + * @public + * @category Type + * @section Swap + */ export type WatchSwapProvidersReturnType = () => void; /** - * Watch for new swap providers registration + * Subscribe to swap provider lifecycle — fires `onChange` whenever a new provider is registered or the default swap provider switches. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link WatchSwapProvidersParameters} Update callback. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @sample docs/examples/src/appkit/actions/swap#WATCH_SWAP_PROVIDERS + * @expand parameters + * + * @public + * @category Action + * @section Swap */ export const watchSwapProviders = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/transaction/create-transfer-ton-transaction.ts b/packages/appkit/src/actions/transaction/create-transfer-ton-transaction.ts index bf84ad836..175cf1a77 100644 --- a/packages/appkit/src/actions/transaction/create-transfer-ton-transaction.ts +++ b/packages/appkit/src/actions/transaction/create-transfer-ton-transaction.ts @@ -6,29 +6,54 @@ * */ -import { createCommentPayloadBase64, parseUnits } from '@ton/walletkit'; - -import type { TransactionRequest, TransactionRequestMessage } from '../../types/transaction'; import type { AppKit } from '../../core/app-kit'; +import type { TransactionRequest, TransactionRequestMessage } from '../../types/transaction'; +import type { Base64String, UserFriendlyAddress } from '../../types/primitives'; +import { createCommentPayloadBase64, parseUnits } from '../../utils'; import { getSelectedWallet } from '../wallets/get-selected-wallet'; +/** + * Parameters accepted by {@link createTransferTonTransaction} and {@link transferTon}. + * + * @public + * @category Type + * @section Transactions + */ export interface CreateTransferTonTransactionParameters { - /** Recipient address */ - recipientAddress: string; - /** Amount in TONs */ + /** Recipient address. */ + recipientAddress: UserFriendlyAddress; + /** Amount in TON as a human-readable decimal string (e.g., `"1.5"`). Converted to nano-TON internally. */ amount: string; - /** Human-readable text comment (will be converted to payload) */ + /** Human-readable text comment. Converted to a Base64 payload when no `payload` is supplied. */ comment?: string; - /** Message payload data encoded in Base64 (overrides comment if provided) */ - payload?: string; - /** Initial state for deploying a new contract, encoded in Base64 */ - stateInit?: string; + /** Raw Base64 message payload — wins over `comment` when both are set. */ + payload?: Base64String; + /** Initial state for deploying a new contract, encoded as Base64. */ + stateInit?: Base64String; } +/** + * Return type of {@link createTransferTonTransaction}. + * + * @public + * @category Type + * @section Transactions + */ export type CreateTransferTonTransactionReturnType = TransactionRequest; /** - * Create a TON transfer transaction request + * Build a TON transfer {@link TransactionRequest} for the selected wallet without sending it — useful when the UI needs to inspect or batch transactions before signing. Throws `Error('Wallet not connected')` if no wallet is currently selected. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link CreateTransferTonTransactionParameters} Recipient, amount and optional payload/comment/stateInit. + * @returns Transaction request ready to pass to `sendTransaction`. + * + * @sample docs/examples/src/appkit/actions/transaction#CREATE_TRANSFER_TON_TRANSACTION + * @expand parameters + * + * @public + * @category Action + * @section Transactions */ export const createTransferTonTransaction = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/transaction/get-transaction-status.ts b/packages/appkit/src/actions/transaction/get-transaction-status.ts index dd250b7a4..9909b60cb 100644 --- a/packages/appkit/src/actions/transaction/get-transaction-status.ts +++ b/packages/appkit/src/actions/transaction/get-transaction-status.ts @@ -6,50 +6,56 @@ * */ -import type { TransactionStatusResponse } from '@ton/walletkit'; -import { getTransactionStatus as walletKitGetTransactionStatus } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; import type { Network } from '../../types/network'; +import type { TransactionStatusResponse } from '../../types/transaction'; +import { getTransactionStatusFromClient as walletKitGetTransactionStatus } from '../../utils'; import { resolveNetwork } from '../../utils/network/resolve-network'; +/** + * Parameters accepted by {@link getTransactionStatus} — must carry exactly one of `boc` or `normalizedHash`, plus an optional network override. + * + * @public + * @category Type + * @section Transactions + */ export type GetTransactionStatusParameters = { - /** Network to check the transaction on */ + /** Network to check the transaction on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; } & ( | { - /** BOC of the sent transaction (base64) */ + /** Base64-encoded BoC of the sent transaction (returned by {@link sendTransaction}). */ boc: string; - /** Hash of the sent transaction (hex) */ normalizedHash?: never; } | { - /** BOC of the sent transaction (base64) */ boc?: never; - /** Normalized Hash of the external-in transaction (hex) */ + /** Hex-encoded normalized hash of the external-in message (returned by {@link sendTransaction} as `normalizedHash`). */ normalizedHash: string; } ); +/** + * Return type of {@link getTransactionStatus}. + * + * @public + * @category Type + * @section Transactions + */ export type GetTransactionStatusReturnType = TransactionStatusResponse; export type GetTransactionStatusErrorType = Error; /** - * Get the status of a transaction by its BOC. + * Read the status of a sent transaction by its BoC or normalized hash. In TON a single external message triggers a tree of internal messages — the transaction is `'completed'` only when the entire trace finishes. Until then it stays `'pending'`. Throws when neither `boc` nor `normalizedHash` is provided. * - * In TON, a single external message triggers a tree of internal messages. - * The transaction is "complete" only when the entire trace finishes. - * This action checks toncenter's trace endpoints to determine the current status. + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link GetTransactionStatusParameters} Exactly one of `boc` or `normalizedHash`, plus an optional network override. + * @returns Status response with current state, completed/total message counts and trace details. * - * @example - * ```ts - * const result = await sendTransaction(appKit, { messages: [...] }); - * const status = await getTransactionStatus(appKit, { boc: result.boc }); - * // status.status === 'pending' | 'completed' | 'failed' - * // status.completedMessages === 3 - * // status.totalMessages === 5 - * ``` + * @public + * @category Action + * @section Transactions */ export const getTransactionStatus = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/transaction/send-transaction.ts b/packages/appkit/src/actions/transaction/send-transaction.ts index 723d952d2..26af74a37 100644 --- a/packages/appkit/src/actions/transaction/send-transaction.ts +++ b/packages/appkit/src/actions/transaction/send-transaction.ts @@ -6,20 +6,42 @@ * */ -import type { SendTransactionResponse } from '@ton/walletkit'; - -import type { TransactionRequest } from '../../types/transaction'; import type { AppKit } from '../../core/app-kit'; +import type { TransactionRequest, SendTransactionResponse } from '../../types/transaction'; import { getSelectedWallet } from '../wallets/get-selected-wallet'; +/** + * Parameters accepted by {@link sendTransaction} — same shape as {@link TransactionRequest}. + * + * @public + * @category Type + * @section Transactions + */ export type SendTransactionParameters = TransactionRequest; +/** + * Return type of {@link sendTransaction}. + * + * @public + * @category Type + * @section Transactions + */ export type SendTransactionReturnType = SendTransactionResponse; export type SendTransactionErrorType = Error; /** - * Send transaction + * Hand a pre-built {@link TransactionRequest} to the selected wallet for signing and broadcast — usually the second step after {@link createTransferTonTransaction}, {@link buildSwapTransaction} or {@link buildStakeTransaction}. Throws `Error('Wallet not connected')` if no wallet is currently selected. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link SendTransactionParameters} Transaction request to broadcast. + * @returns Wallet response carrying the BoC of the sent transaction. + * + * @sample docs/examples/src/appkit/actions/transaction#SEND_TRANSACTION + * + * @public + * @category Action + * @section Transactions */ export const sendTransaction = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/transaction/transfer-ton.ts b/packages/appkit/src/actions/transaction/transfer-ton.ts index 530e75da9..d7608bf13 100644 --- a/packages/appkit/src/actions/transaction/transfer-ton.ts +++ b/packages/appkit/src/actions/transaction/transfer-ton.ts @@ -6,21 +6,45 @@ * */ -import type { SendTransactionResponse } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { SendTransactionResponse } from '../../types/transaction'; import { createTransferTonTransaction } from './create-transfer-ton-transaction'; import type { CreateTransferTonTransactionParameters } from './create-transfer-ton-transaction'; import { sendTransaction } from './send-transaction'; +/** + * Parameters accepted by {@link transferTon} — same shape as {@link CreateTransferTonTransactionParameters}. + * + * @public + * @category Type + * @section Transactions + */ export type TransferTonParameters = CreateTransferTonTransactionParameters; +/** + * Return type of {@link transferTon}. + * + * @public + * @category Type + * @section Transactions + */ export type TransferTonReturnType = SendTransactionResponse; export type TransferTonErrorType = Error; /** - * Transfer TON - creates and sends a TON transfer transaction + * Build and send a TON transfer from the selected wallet in one step (use {@link createTransferTonTransaction} + {@link sendTransaction} if you need to inspect the transaction first). Throws `Error('Wallet not connected')` if no wallet is currently selected. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link TransferTonParameters} Recipient, amount and optional payload/comment/stateInit. + * @returns Wallet response carrying the BoC of the sent transaction. + * + * @sample docs/examples/src/appkit/actions/transaction#TRANSFER_TON + * @expand parameters + * + * @public + * @category Action + * @section Transactions */ export const transferTon = async ( appKit: AppKit, diff --git a/packages/appkit/src/actions/transaction/watch-transactions-by-address.ts b/packages/appkit/src/actions/transaction/watch-transactions-by-address.ts index cf9e62724..3a7ae52be 100644 --- a/packages/appkit/src/actions/transaction/watch-transactions-by-address.ts +++ b/packages/appkit/src/actions/transaction/watch-transactions-by-address.ts @@ -7,21 +7,50 @@ */ import { Address } from '@ton/core'; -import type { TransactionsUpdate, Network } from '@ton/walletkit'; import type { AppKit } from '../../core/app-kit'; +import type { TransactionsUpdate } from '../../core/streaming'; +import type { Network } from '../../types/network'; +import type { UserFriendlyAddress } from '../../types/primitives'; import { resolveNetwork } from '../../utils/network/resolve-network'; +/** + * Options for {@link watchTransactionsByAddress}. + * + * @public + * @category Type + * @section Transactions + */ export interface WatchTransactionsByAddressOptions { - address: string | Address; + /** Address to watch — pass a {@link UserFriendlyAddress} string or an `Address` instance from `@ton/core`. */ + address: UserFriendlyAddress | Address; + /** Callback fired on every transactions update from the streaming provider. */ onChange: (update: TransactionsUpdate) => void; + /** Network to watch on. Defaults to the selected wallet's network. If no wallet is selected, falls back to AppKit's default network, or mainnet when none is set. */ network?: Network; } +/** + * Return type of {@link watchTransactionsByAddress} — call to stop receiving updates. + * + * @public + * @category Type + * @section Transactions + */ export type WatchTransactionsByAddressReturnType = () => void; /** - * Watch transactions by address. + * Subscribe to incoming-transaction events for an arbitrary address (use {@link watchTransactions} for the selected wallet). Requires a streaming provider registered for the network — call throws when none is configured. Use {@link hasStreamingProvider} to check first. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link WatchTransactionsByAddressOptions} Address, update callback and optional network override. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @expand options + * + * @public + * @category Action + * @section Transactions */ export const watchTransactionsByAddress = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/transaction/watch-transactions.ts b/packages/appkit/src/actions/transaction/watch-transactions.ts index 4ad39c1aa..8b78c471e 100644 --- a/packages/appkit/src/actions/transaction/watch-transactions.ts +++ b/packages/appkit/src/actions/transaction/watch-transactions.ts @@ -6,22 +6,48 @@ * */ -import type { TransactionsUpdate, Network } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; import { WALLETS_EVENTS } from '../../core/app-kit'; +import type { TransactionsUpdate } from '../../core/streaming'; +import type { Network } from '../../types/network'; import { getSelectedWallet } from '../wallets/get-selected-wallet'; import { watchTransactionsByAddress } from './watch-transactions-by-address'; +/** + * Options for {@link watchTransactions}. + * + * @public + * @category Type + * @section Transactions + */ export interface WatchTransactionsOptions { + /** Callback fired on every transactions update from the streaming provider. */ onChange: (update: TransactionsUpdate) => void; + /** Network to watch on. Defaults to the selected wallet's network. */ network?: Network; } +/** + * Return type of {@link watchTransactions} — call to stop receiving updates. + * + * @public + * @category Type + * @section Transactions + */ export type WatchTransactionsReturnType = () => void; /** - * Watch transactions for the selected wallet. + * Subscribe to incoming-transaction events for the currently selected wallet, automatically rebinding when the user connects, switches, or disconnects (use {@link watchTransactionsByAddress} for a fixed address). Requires a streaming provider registered for the network — call throws when none is configured. Use {@link hasStreamingProvider} to check first. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param options - {@link WatchTransactionsOptions} Update callback and optional network override. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @expand options + * + * @public + * @category Action + * @section Transactions */ export const watchTransactions = (appKit: AppKit, options: WatchTransactionsOptions): WatchTransactionsReturnType => { const { network, onChange } = options; diff --git a/packages/appkit/src/actions/wallets/get-connected-wallets.ts b/packages/appkit/src/actions/wallets/get-connected-wallets.ts index dbc8ed25e..24746335e 100644 --- a/packages/appkit/src/actions/wallets/get-connected-wallets.ts +++ b/packages/appkit/src/actions/wallets/get-connected-wallets.ts @@ -9,10 +9,26 @@ import type { AppKit } from '../../core/app-kit'; import type { WalletInterface } from '../../types/wallet'; +/** + * Return type of {@link getConnectedWallets} — read-only view of the connected-wallets array. + * + * @public + * @category Type + * @section Wallets + */ export type GetConnectedWalletsReturnType = readonly WalletInterface[]; /** - * Get connected wallets + * List every wallet currently connected through any registered {@link Connector}. + * + * @param appKit - {@link AppKit} Runtime instance. + * @returns Read-only array of {@link WalletInterface}s. + * + * @sample docs/examples/src/appkit/actions/wallets#GET_CONNECTED_WALLETS + * + * @public + * @category Action + * @section Wallets */ export const getConnectedWallets = (appKit: AppKit): GetConnectedWalletsReturnType => { return appKit.walletsManager.wallets; diff --git a/packages/appkit/src/actions/wallets/get-selected-wallet.ts b/packages/appkit/src/actions/wallets/get-selected-wallet.ts index 0512e010b..4f90b299f 100644 --- a/packages/appkit/src/actions/wallets/get-selected-wallet.ts +++ b/packages/appkit/src/actions/wallets/get-selected-wallet.ts @@ -9,10 +9,26 @@ import type { AppKit } from '../../core/app-kit'; import type { WalletInterface } from '../../types/wallet'; +/** + * Return type of {@link getSelectedWallet} — `null` when no wallet is currently selected. + * + * @public + * @category Type + * @section Wallets + */ export type GetSelectedWalletReturnType = WalletInterface | null; /** - * Get currently selected wallet + * Read the wallet AppKit treats as "active" — most actions ({@link getBalance}, {@link signText}, {@link transferTon}) target this wallet implicitly. Returns `null` when no wallet is connected or selected. + * + * @param appKit - {@link AppKit} Runtime instance. + * @returns Selected {@link WalletInterface}, or `null` when none is selected. + * + * @sample docs/examples/src/appkit/actions/wallets#GET_SELECTED_WALLET + * + * @public + * @category Action + * @section Wallets */ export const getSelectedWallet = (appKit: AppKit): GetSelectedWalletReturnType => { return appKit.walletsManager.selectedWallet; diff --git a/packages/appkit/src/actions/wallets/set-selected-wallet-id.ts b/packages/appkit/src/actions/wallets/set-selected-wallet-id.ts index 8ca697fc0..ceb3bfaf9 100644 --- a/packages/appkit/src/actions/wallets/set-selected-wallet-id.ts +++ b/packages/appkit/src/actions/wallets/set-selected-wallet-id.ts @@ -8,14 +8,39 @@ import type { AppKit } from '../../core/app-kit'; +/** + * Parameters accepted by {@link setSelectedWalletId}. + * + * @public + * @category Type + * @section Wallets + */ export interface SetSelectedWalletIdParameters { + /** Wallet ID (as returned by {@link WalletInterface}'s `getWalletId()`) to select. Pass `null` to clear the selection. */ walletId: string | null; } +/** + * Return type of {@link setSelectedWalletId}. + * + * @public + * @category Type + * @section Wallets + */ export type SetSelectedWalletIdReturnType = void; /** - * Set selected wallet + * Switch which connected wallet AppKit treats as selected — emits `WALLETS_EVENTS.SELECTION_CHANGED` so {@link watchSelectedWallet} subscribers fire. Pass `null` to clear the selection. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link SetSelectedWalletIdParameters} Wallet ID to select, or `null` to clear. + * + * @sample docs/examples/src/appkit/actions/wallets#SET_SELECTED_WALLET_ID + * @expand parameters + * + * @public + * @category Action + * @section Wallets */ export const setSelectedWalletId = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/wallets/watch-connected-wallets.ts b/packages/appkit/src/actions/wallets/watch-connected-wallets.ts index 3c0db1f60..c2d38f992 100644 --- a/packages/appkit/src/actions/wallets/watch-connected-wallets.ts +++ b/packages/appkit/src/actions/wallets/watch-connected-wallets.ts @@ -10,14 +10,40 @@ import type { AppKit } from '../../core/app-kit'; import { WALLETS_EVENTS } from '../../core/app-kit'; import type { WalletInterface } from '../../types/wallet'; +/** + * Parameters accepted by {@link watchConnectedWallets}. + * + * @public + * @category Type + * @section Wallets + */ export type WatchConnectedWalletsParameters = { + /** Callback fired whenever the list of connected wallets changes — receives the latest snapshot. */ onChange: (wallets: WalletInterface[]) => void; }; +/** + * Return type of {@link watchConnectedWallets} — call to stop receiving updates. + * + * @public + * @category Type + * @section Wallets + */ export type WatchConnectedWalletsReturnType = () => void; /** - * Watch connected wallets + * Subscribe to the list of connected wallets — fires whenever a wallet connects or disconnects through any registered {@link Connector}. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link WatchConnectedWalletsParameters} Update callback. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @sample docs/examples/src/appkit/actions/wallets#WATCH_CONNECTED_WALLETS + * @expand parameters + * + * @public + * @category Action + * @section Wallets */ export const watchConnectedWallets = ( appKit: AppKit, diff --git a/packages/appkit/src/actions/wallets/watch-selected-wallet.ts b/packages/appkit/src/actions/wallets/watch-selected-wallet.ts index 22bee3a7b..1a7fbdb1e 100644 --- a/packages/appkit/src/actions/wallets/watch-selected-wallet.ts +++ b/packages/appkit/src/actions/wallets/watch-selected-wallet.ts @@ -11,14 +11,40 @@ import { WALLETS_EVENTS } from '../../core/app-kit'; import { getSelectedWallet } from '../../actions'; import type { WalletInterface } from '../../types/wallet'; +/** + * Parameters accepted by {@link watchSelectedWallet}. + * + * @public + * @category Type + * @section Wallets + */ export interface WatchSelectedWalletParameters { + /** Callback fired whenever the selected wallet changes — receives the new wallet, or `null` when the selection was cleared. */ onChange: (wallet: WalletInterface | null) => void; } +/** + * Return type of {@link watchSelectedWallet} — call to stop receiving updates. + * + * @public + * @category Type + * @section Wallets + */ export type WatchSelectedWalletReturnType = () => void; /** - * Watch selected wallet + * Subscribe to selected-wallet changes — fires when {@link setSelectedWalletId} runs, when the wallet manager auto-selects the first wallet because no prior selection survived a connector update, or when it clears the selection because no connected wallets remain. + * + * @param appKit - {@link AppKit} Runtime instance. + * @param parameters - {@link WatchSelectedWalletParameters} Update callback. + * @returns Unsubscribe function — call it to stop receiving updates. + * + * @sample docs/examples/src/appkit/actions/wallets#WATCH_SELECTED_WALLET + * @expand parameters + * + * @public + * @category Action + * @section Wallets */ export const watchSelectedWallet = ( appKit: AppKit, diff --git a/packages/appkit/src/connectors/tonconnect/adapters/ton-connect-wallet-adapter.ts b/packages/appkit/src/connectors/tonconnect/adapters/ton-connect-wallet-adapter.ts index d7db5c564..f1a123f0b 100644 --- a/packages/appkit/src/connectors/tonconnect/adapters/ton-connect-wallet-adapter.ts +++ b/packages/appkit/src/connectors/tonconnect/adapters/ton-connect-wallet-adapter.ts @@ -9,35 +9,48 @@ import { Address } from '@ton/core'; import type { Wallet as TonConnectWallet } from '@tonconnect/sdk'; import type { SignDataPayload as TonConnectSignDataPayload } from '@tonconnect/sdk'; -import type { SendTransactionResponse, UserFriendlyAddress, Hex } from '@ton/walletkit'; -import { asHex, createWalletId, getNormalizedExtMessageHash } from '@ton/walletkit'; import type { TonConnectUI } from '@tonconnect/ui'; -import type { TransactionRequest } from '../../../types/transaction'; -import type { Base64String } from '../../../types/primitives'; -import { getValidUntil } from '../utils/transaction'; -import type { WalletInterface } from '../../../types/wallet'; -import type { SignDataRequest, SignDataResponse } from '../../../types/signing'; import { Network } from '../../../types/network'; +import type { Base64String, UserFriendlyAddress, Hex } from '../../../types/primitives'; +import type { SignDataRequest, SignDataResponse } from '../../../types/signing'; +import type { TransactionRequest, SendTransactionResponse } from '../../../types/transaction'; +import type { WalletInterface } from '../../../types/wallet'; +import { asHex, createWalletId, getNormalizedExtMessageHash } from '../../../utils'; +import { getValidUntil } from '../utils/transaction'; /** - * Configuration for TonConnectWalletAdapter + * Configuration accepted by {@link TonConnectWalletAdapter} when wrapping a TonConnect wallet for AppKit. + * + * @public + * @category Type + * @section Wallets */ export interface TonConnectWalletAdapterConfig { + /** ID of the connector that produced this wallet — surfaced as `WalletInterface.connectorId`. */ connectorId: string; + /** Underlying TonConnect wallet object. */ tonConnectWallet: TonConnectWallet; + /** TonConnect UI instance used to drive `sendTransaction` and `signData` calls. */ tonConnectUI: TonConnectUI; } /** - * Minimal adapter that makes TonConnect wallet compatible with WalletInterface. - * Only implements identity and signing methods - data fetching is done via actions. + * {@link WalletInterface} implementation backed by a TonConnect wallet. Prefer the {@link createTonConnectConnector} factory over instantiating this class directly — the connector builds the adapter for every wallet it tracks and apps interact with it through standard AppKit actions ({@link sendTransaction}, {@link signText}/{@link signBinary}/{@link signCell}). On-chain reads (balance, jettons, NFTs) live on separate actions ({@link getBalance}, {@link getJettons}, {@link getNfts}) and don't go through this adapter. + * + * @public + * @category Class + * @section Wallets */ export class TonConnectWalletAdapter implements WalletInterface { public readonly tonConnectWallet: TonConnectWallet; public readonly tonConnectUI: TonConnectUI; public readonly connectorId: string; + /** + * @param config - {@link TonConnectWalletAdapterConfig} TonConnect wallet + UI instance and the id of the connector that produced them. + * @expand config + */ constructor(config: TonConnectWalletAdapterConfig) { this.tonConnectWallet = config.tonConnectWallet; this.tonConnectUI = config.tonConnectUI; diff --git a/packages/appkit/src/connectors/tonconnect/connectors/ton-connect-connector.ts b/packages/appkit/src/connectors/tonconnect/connectors/ton-connect-connector.ts index f3454623e..9fbd4dab5 100644 --- a/packages/appkit/src/connectors/tonconnect/connectors/ton-connect-connector.ts +++ b/packages/appkit/src/connectors/tonconnect/connectors/ton-connect-connector.ts @@ -16,20 +16,52 @@ import type { WalletInterface } from '../../../types/wallet'; import { TONCONNECT_DEFAULT_CONNECTOR_ID } from '../constants/id'; import { createConnector } from '../../../types/connector'; +/** + * Configuration accepted by {@link createTonConnectConnector}. + * + * @public + * @category Type + * @section Connectors + */ export interface TonConnectConnectorConfig { + /** Connector ID. Defaults to {@link TONCONNECT_DEFAULT_CONNECTOR_ID} (`'tonconnect'`). Set this when you need to register multiple TonConnect-flavoured connectors side by side. */ id?: string; + /** Display metadata override. Merged on top of TonConnect's default name and icon. */ metadata?: ConnectorMetadata; + /** Options forwarded to the underlying `TonConnectUI` constructor (manifest URL, etc.). Ignored when `tonConnectUI` is supplied. */ tonConnectOptions?: TonConnectUiCreateOptions; + /** Pre-built `TonConnectUI` instance to reuse. When set, the connector skips its own instantiation and `tonConnectOptions` is ignored. */ tonConnectUI?: TonConnectUI; } +/** + * {@link Connector} produced by {@link createTonConnectConnector} — extends the base interface with the underlying `TonConnectUI` instance for advanced flows that need direct access (e.g., custom modals). + * + * @public + * @category Type + * @section Connectors + */ export type TonConnectConnector = Connector & { type: 'tonconnect'; + /** Underlying `TonConnectUI` instance — `null` during SSR or before the connector has been initialised. Apps that need to drive the modal directly (e.g. custom UI flows) can read this and call its methods. */ tonConnectUI: TonConnectUI | null; }; +/** + * Build a TonConnect-backed {@link Connector} for AppKit. Pass the result to {@link AppKitConfig}'s `connectors` or {@link addConnector}. + * + * @param config - {@link TonConnectConnectorConfig} Connector ID, metadata override and TonConnect options or pre-built UI instance. + * @returns Factory function consumed by AppKit at registration time. + * @expand config + * + * @sample docs/examples/src/appkit/connectors/tonconnect#TON_CONNECT_CONNECTOR + * + * @public + * @category Action + * @section Connectors + */ export const createTonConnectConnector = (config: TonConnectConnectorConfig) => { - return createConnector(({ eventEmitter, networkManager, ssr }): TonConnectConnector => { + return createConnector(({ eventEmitter, networkManager }): TonConnectConnector => { let originalTonConnectUI: TonConnectUI | null = null; let unsubscribeTonConnect: (() => void) | null = null; let unsubscribeDefaultNetwork: (() => void) | null = null; @@ -46,7 +78,7 @@ export const createTonConnectConnector = (config: TonConnectConnectorConfig) => return originalTonConnectUI; } - if (ssr && typeof window === 'undefined') { + if (typeof window === 'undefined') { return null; } diff --git a/packages/appkit/src/connectors/tonconnect/constants/id.ts b/packages/appkit/src/connectors/tonconnect/constants/id.ts index 17b334637..46439665b 100644 --- a/packages/appkit/src/connectors/tonconnect/constants/id.ts +++ b/packages/appkit/src/connectors/tonconnect/constants/id.ts @@ -6,4 +6,11 @@ * */ +/** + * Default id assigned to the TonConnect connector when none is supplied to {@link createTonConnectConnector}. Pass this to {@link connect} / {@link disconnect} to drive the TonConnect flow without hard-coding the literal. + * + * @public + * @category Constants + * @section Connectors + */ export const TONCONNECT_DEFAULT_CONNECTOR_ID = 'tonconnect'; diff --git a/packages/appkit/src/connectors/tonconnect/index.ts b/packages/appkit/src/connectors/tonconnect/index.ts index 993c740b8..ea4d9cc56 100644 --- a/packages/appkit/src/connectors/tonconnect/index.ts +++ b/packages/appkit/src/connectors/tonconnect/index.ts @@ -7,17 +7,11 @@ */ /** - * TonConnect Feature Entry Point - * - * This module contains all TonConnect-related functionality. - * Import from '@ton/appkit/tonconnect' to use TonConnect features. - * - * This is a separate entry point to allow tree-shaking for users - * who don't need TonConnect functionality. + * TonConnect entry point. Import from `@ton/appkit/tonconnect`. It's kept as a separate * entry so apps that don't use TonConnect can tree-shake it out. * * @example * ```ts - * import { TonConnectConnector, TonConnectWalletWrapper } from '@ton/appkit/tonconnect'; + * import { createTonConnectConnector, TonConnectWalletAdapter } from '@ton/appkit/tonconnect'; * ``` */ diff --git a/packages/appkit/src/connectors/tonconnect/utils/transaction.ts b/packages/appkit/src/connectors/tonconnect/utils/transaction.ts index 2d6d10069..b7105f910 100644 --- a/packages/appkit/src/connectors/tonconnect/utils/transaction.ts +++ b/packages/appkit/src/connectors/tonconnect/utils/transaction.ts @@ -16,7 +16,7 @@ import type { TransactionRequest, TransactionRequestMessage } from '../../../typ export const DEFAULT_TRANSACTION_VALIDITY_SECONDS = 300; /** - * Convert TonWalletKit TransactionRequest to TonConnect SendTransactionRequest format + * Convert a walletkit `TransactionRequest` to a TonConnect `SendTransactionRequest`. */ export const toTonConnectTransaction = (request: TransactionRequest): SendTransactionRequest => { return { @@ -26,7 +26,7 @@ export const toTonConnectTransaction = (request: TransactionRequest): SendTransa }; /** - * Convert a single TransactionRequestMessage to TonConnect message format + * Convert a single TransactionRequestMessage to TonConnect message format. */ export const toTonConnectMessage = ( msg: TransactionRequestMessage, @@ -45,7 +45,7 @@ export const toTonConnectMessage = ( }; /** - * Get current timestamp plus validity duration + * Get current timestamp plus validity duration. */ export const getValidUntil = (validitySeconds = DEFAULT_TRANSACTION_VALIDITY_SECONDS): number => { return Math.floor(Date.now() / 1000) + validitySeconds; diff --git a/packages/appkit/src/core/app-kit/constants/events.ts b/packages/appkit/src/core/app-kit/constants/events.ts index 54d645101..14ec52a5c 100644 --- a/packages/appkit/src/core/app-kit/constants/events.ts +++ b/packages/appkit/src/core/app-kit/constants/events.ts @@ -7,16 +7,27 @@ */ /** - * Connector events + * Event names AppKit emits for connector-list and connector-wallet changes. Payloads are {@link ConnectorAddedPayload}, {@link ConnectorRemovedPayload} and {@link ConnectorWalletsUpdatedPayload}. + * + * @public + * @category Constants + * @section Connectors */ export const CONNECTOR_EVENTS = { + /** A connector was registered via {@link addConnector} (or AppKit's constructor). */ ADDED: 'connector:added', + /** A connector was unregistered — typically by calling the unregister function returned from {@link addConnector}, or as part of the connector's own teardown. */ REMOVED: 'connector:removed', + /** A connector's connected-wallets list changed (connect, disconnect, or account switch inside the wallet). */ WALLETS_UPDATED: 'connector:wallets-updated', } as const; /** - * Wallet events + * Event names AppKit emits when the available wallet list (`UPDATED`) or the active wallet (`SELECTION_CHANGED`) changes. + * + * @public + * @category Constants + * @section Wallets */ export const WALLETS_EVENTS = { UPDATED: 'wallets:updated', @@ -24,7 +35,11 @@ export const WALLETS_EVENTS = { } as const; /** - * Networks events + * Event names AppKit emits on network changes. `DEFAULT_CHANGED` carries a {@link DefaultNetworkChangedPayload}. + * + * @public + * @category Constants + * @section Networks */ export const NETWORKS_EVENTS = { UPDATED: 'networks:updated', diff --git a/packages/appkit/src/core/app-kit/services/app-kit.ts b/packages/appkit/src/core/app-kit/services/app-kit.ts index 44fe38c01..dc4346594 100644 --- a/packages/appkit/src/core/app-kit/services/app-kit.ts +++ b/packages/appkit/src/core/app-kit/services/app-kit.ts @@ -6,29 +6,34 @@ * */ -import { SwapManager, StreamingManager, OnrampManager, CryptoOnrampManager } from '@ton/walletkit'; -import type { - ProviderInput, - SwapProviderInterface, - StakingProviderInterface, - OnrampProviderInterface, - CryptoOnrampProviderInterface, -} from '@ton/walletkit'; - -import type { AppKitConfig } from '../types/config'; -import { CONNECTOR_EVENTS, WALLETS_EVENTS } from '../constants/events'; +import { CryptoOnrampManager } from '../../../crypto-onramp'; +import type { CryptoOnrampProviderInterface } from '../../../crypto-onramp'; +import { OnrampManager } from '../../../onramp'; +import type { OnrampProviderInterface } from '../../../onramp'; import { StakingManager } from '../../../staking'; +import type { StakingProviderInterface } from '../../../staking'; +import { SwapManager } from '../../../swap'; +import type { SwapProviderInterface } from '../../../swap'; import type { Connector, ConnectorFactoryContext, ConnectorInput } from '../../../types/connector'; -import { EventEmitter } from '../../emitter'; -import type { AppKitEmitter, AppKitEvents } from '../types/events'; +import { Network } from '../../../types/network'; +import type { ProviderInput } from '../../../types/provider'; import type { WalletInterface } from '../../../types/wallet'; -import { WalletsManager } from '../../wallets-manager'; +import { EventEmitter } from '../../emitter'; import { AppKitNetworkManager } from '../../network'; -import { Network } from '../../../types/network'; +import { StreamingManager } from '../../streaming'; +import { WalletsManager } from '../../wallets-manager'; +import { CONNECTOR_EVENTS, WALLETS_EVENTS } from '../constants/events'; +import type { AppKitEmitter, AppKitEvents } from '../types/events'; +import type { AppKitConfig } from '../types/config'; /** - * Central hub for wallet management. - * Stores emitter, providers, and manages wallet connections. + * Runtime that wires connectors, networks, providers and the event emitter for a TON dApp. Construct once at startup and reuse for the app's lifetime. + * + * @sample docs/examples/src/appkit#APPKIT_INIT + * + * @public + * @category Class + * @section Core */ export class AppKit { readonly emitter: AppKitEmitter; @@ -43,6 +48,10 @@ export class AppKit { readonly streamingManager: StreamingManager; readonly config: AppKitConfig; + /** + * @param config - {@link AppKitConfig} Networks, connectors, providers and runtime flags. + * @expand config + */ constructor(config: AppKitConfig) { this.config = config; @@ -55,6 +64,9 @@ export class AppKit { }; this.networkManager = new AppKitNetworkManager({ networks }, this.emitter); + if (config.defaultNetwork) { + this.networkManager.setDefaultNetwork(config.defaultNetwork); + } this.walletsManager = new WalletsManager(this.emitter); this.swapManager = new SwapManager(() => this.createFactoryContext()); @@ -77,11 +89,11 @@ export class AppKit { } createFactoryContext(): ConnectorFactoryContext { - return { eventEmitter: this.emitter, networkManager: this.networkManager, ssr: this.config?.ssr }; + return { eventEmitter: this.emitter, networkManager: this.networkManager }; } /** - * Add a wallet connector + * Add a wallet connector. */ addConnector(input: ConnectorInput): () => void { const connector = typeof input === 'function' ? input(this.createFactoryContext()) : input; @@ -102,7 +114,7 @@ export class AppKit { } /** - * Remove a wallet connector + * Remove a wallet connector. */ removeConnector(connector: Connector): void { const id = connector.id; @@ -117,7 +129,7 @@ export class AppKit { } /** - * Add a provider + * Add a provider. */ registerProvider(input: ProviderInput): void { const provider = typeof input === 'function' ? input(this.createFactoryContext()) : input; @@ -140,7 +152,7 @@ export class AppKit { } /** - * Get all connected wallets from all connectors + * Get all connected wallets from all connectors. */ private updateWalletsFromConnectors(): void { const allWallets: WalletInterface[] = []; diff --git a/packages/appkit/src/core/app-kit/types/config.ts b/packages/appkit/src/core/app-kit/types/config.ts index d2cc0b2e0..73c8b160e 100644 --- a/packages/appkit/src/core/app-kit/types/config.ts +++ b/packages/appkit/src/core/app-kit/types/config.ts @@ -6,40 +6,27 @@ * */ -import type { NetworkAdapters, ProviderInput } from '@ton/walletkit'; - import type { ConnectorInput } from '../../../types/connector'; -import type { Network } from '../../../types/network'; +import type { Network, NetworkAdapters } from '../../../types/network'; +import type { ProviderInput } from '../../../types/provider'; /** - * Configuration for AppKit + * Constructor options for {@link AppKit} — networks, connectors, providers and runtime flags. + * + * @public + * @category Type + * @section Core */ export interface AppKitConfig { - /** - * Network configuration - * At least one network must be configured. - * - * Keys are chain IDs (use `Network.mainnet().chainId` or `Network.testnet().chainId`) - * Values contain apiClient configuration (url and optional API key) - */ + /** Map of chain ID to {@link NetworkConfig} (which holds the api-client setup). If omitted, AppKit defaults to mainnet only. */ networks?: NetworkAdapters; - /** - * Wallet connectors - */ + /** Wallet connectors registered at startup. */ connectors?: ConnectorInput[]; - /** - * Default network for wallet connections. - * If set, connectors (e.g. TonConnect) will enforce this network when connecting. - * Set to `undefined` to allow any network. - */ + /** Default network. */ defaultNetwork?: Network; + /** Providers registered at startup. */ providers?: ProviderInput[]; - - /** - * Enable server-side rendering support - */ - ssr?: boolean; } diff --git a/packages/appkit/src/core/app-kit/types/events.ts b/packages/appkit/src/core/app-kit/types/events.ts index e52c78400..6267163e3 100644 --- a/packages/appkit/src/core/app-kit/types/events.ts +++ b/packages/appkit/src/core/app-kit/types/events.ts @@ -13,36 +13,90 @@ import type { SharedKitEvents } from '../../emitter'; import type { EventEmitter } from '../../emitter'; import type { WalletInterface } from '../../../types/wallet'; +/** + * Payload of `connector:added` events — the connector that was just registered. + * + * @public + * @category Type + * @section Core + */ export interface ConnectorAddedPayload { + /** The {@link Connector} that was just registered with AppKit. */ connector: Connector; } +/** + * Payload of `connector:removed` events — the connector that was just unregistered. + * + * @public + * @category Type + * @section Core + */ export interface ConnectorRemovedPayload { + /** The {@link Connector} that was just unregistered from AppKit (already torn down via `destroy()`). */ connector: Connector; } +/** + * Payload of `connector:wallets-updated` events — fired by a connector when its connected-wallets list changes (connect, disconnect, or account switch inside the wallet). + * + * @public + * @category Type + * @section Core + */ export interface ConnectorWalletsUpdatedPayload { + /** ID of the {@link Connector} whose wallets just changed. */ connectorId: string; + /** Wallets currently exposed by the connector — empty when the wallet was just disconnected. */ wallets: WalletInterface[]; } +/** + * Payload of `networks:default-changed` events — the new default network, or `undefined` when cleared. + * + * @public + * @category Type + * @section Core + */ export interface DefaultNetworkChangedPayload { + /** New default network, or `undefined` when the constraint is cleared. */ network: Network | undefined; } +/** + * Map of every event name AppKit can emit to its payload type, used to type listeners on {@link AppKitEmitter}. + * + * @public + * @category Type + * @section Core + */ export type AppKitEvents = { // Connector events + /** Fired by {@link addConnector} when a connector is registered with AppKit. */ [CONNECTOR_EVENTS.ADDED]: ConnectorAddedPayload; + /** Fired when a connector is unregistered from AppKit — typically by calling the unregister function returned from {@link addConnector}. */ [CONNECTOR_EVENTS.REMOVED]: ConnectorRemovedPayload; + /** Fired by a connector whenever its connected-wallets list changes (connect, disconnect, or account switch inside the wallet). */ [CONNECTOR_EVENTS.WALLETS_UPDATED]: ConnectorWalletsUpdatedPayload; // Wallets events + /** Fired by AppKit's wallet manager after re-aggregating connectors — `wallets` is the full current set. */ [WALLETS_EVENTS.UPDATED]: { wallets: WalletInterface[] }; + /** Fired when the selected wallet changes — `walletId` is the new selection, or `null` when cleared. */ [WALLETS_EVENTS.SELECTION_CHANGED]: { walletId: string | null }; // Networks events + /** Fired by the network manager when a network's API client is registered or replaced via `setClient`. */ [NETWORKS_EVENTS.UPDATED]: Record; + /** Fired by {@link setDefaultNetwork} — carries the new default network, or `undefined` when the constraint was cleared. */ [NETWORKS_EVENTS.DEFAULT_CHANGED]: DefaultNetworkChangedPayload; } & SharedKitEvents; +/** + * Strongly-typed event emitter accessed through `appKit.emitter`. `appKit.emitter.on(name, handler)` returns an unsubscribe function. + * + * @public + * @category Type + * @section Core + */ export type AppKitEmitter = EventEmitter; diff --git a/packages/appkit/src/core/emitter/index.ts b/packages/appkit/src/core/emitter/index.ts index 415f6bb99..ad05766fc 100644 --- a/packages/appkit/src/core/emitter/index.ts +++ b/packages/appkit/src/core/emitter/index.ts @@ -7,9 +7,61 @@ */ /** - * Events Feature - * Provides Emitter implementation + * Strongly-typed event emitter built on a string event name → payload type map. Type of `appKit.emitter` and the base for any custom emitters apps create. See {@link AppKitEvents} for the full list of events AppKit emits. `appKit.emitter.on(name, handler)` returns an unsubscribe function. + * + * @extract + * @public + * @category Class + * @section Core */ export { EventEmitter } from '@ton/walletkit'; -export type { EventPayload, KitEvent, EventListener, SharedKitEvents } from '@ton/walletkit'; +/** + * Generic event-payload constraint — an `object` that the typed event-name → payload map maps to. + * + * @extract + * @public + * @category Type + * @section Core + */ +export type { EventPayload } from '@ton/walletkit'; + +/** + * Envelope every {@link EventEmitter} listener receives — `type` is the event name, `payload` is the event-specific data, `source` identifies who emitted it, and `timestamp` is the wall-clock millisecond mark. + * + * @extract + * @public + * @category Type + * @section Core + */ +export type { KitEvent } from '@ton/walletkit'; + +/** + * Listener callback signature accepted by {@link EventEmitter}'s `on` — receives a {@link KitEvent} for the given event type and may return a Promise the emitter awaits. + * + * @extract + * @public + * @category Type + * @section Core + */ +export type { EventListener } from '@ton/walletkit'; + +/** + * Event-name → payload map shared between AppKit and walletkit. AppKit extends it with its own connector, wallet and network events to type {@link AppKitEmitter}. + * + * @extract + * @public + * @category Type + * @section Core + */ +export type { SharedKitEvents } from '@ton/walletkit'; + +/** + * Payload of `provider:registered` and `provider:default-changed` events — carries the affected provider's id and kind. + * + * @extract + * @public + * @category Type + * @section Core + */ +export type { BaseProviderUpdate } from '@ton/walletkit'; diff --git a/packages/appkit/src/core/network/index.ts b/packages/appkit/src/core/network/index.ts index 7434fc17d..e66f550be 100644 --- a/packages/appkit/src/core/network/index.ts +++ b/packages/appkit/src/core/network/index.ts @@ -7,4 +7,5 @@ */ export { AppKitNetworkManager } from './services/app-kit-network-manager'; -export { ApiClient, ApiClientToncenter, ApiClientTonApi } from '@ton/walletkit'; +export { ApiClient, ApiClientToncenter, ApiClientTonApi, KitNetworkManager } from './walletkit'; +export type { ApiClientToncenterConfig, BaseApiClientConfig } from './walletkit'; diff --git a/packages/appkit/src/core/network/services/app-kit-network-manager.ts b/packages/appkit/src/core/network/services/app-kit-network-manager.ts index d49e94a83..63c404ff2 100644 --- a/packages/appkit/src/core/network/services/app-kit-network-manager.ts +++ b/packages/appkit/src/core/network/services/app-kit-network-manager.ts @@ -6,32 +6,42 @@ * */ -import type { ApiClient } from '@ton/walletkit'; -import { KitNetworkManager } from '@ton/walletkit'; - +import type { ApiClient } from '../../../types/api-client'; +import type { Network } from '../../../types/network'; import { NETWORKS_EVENTS } from '../../app-kit/constants/events'; import type { AppKitEmitter } from '../../app-kit/types/events'; -import type { Network } from '../../../types/network'; +import { KitNetworkManager } from '../walletkit'; +/** + * Network manager that extends walletkit's {@link KitNetworkManager} with a default-network setter and AppKit event emission. Usually accessed through the higher-level actions ({@link getDefaultNetwork}, {@link setDefaultNetwork}, {@link watchDefaultNetwork}, {@link getNetworks}, {@link watchNetworks}). + * + * @public + * @category Class + * @section Networks + */ export class AppKitNetworkManager extends KitNetworkManager { private emitter: AppKitEmitter; private defaultNetwork: Network | undefined = undefined; + /** + * @param options - {@link TonWalletKitOptions} Forwarded to the {@link KitNetworkManager} base — chiefly the `networks` map keyed by chain ID. + * @param emitter - {@link AppKitEmitter} Emitter the manager publishes `networks:default-changed` / `networks:updated` events through. + */ constructor(options: ConstructorParameters[0], emitter: AppKitEmitter) { super(options); this.emitter = emitter; } /** - * Get the current default network + * Get the current default network. */ getDefaultNetwork(): Network | undefined { return this.defaultNetwork; } /** - * Set the default network for wallet connections. - * Emits a change event and propagates to all connectors. + * Set the default network for wallet connections. Emits `networks:default-changed`; + * connectors that listen for it (e.g., TonConnect) can re-bind their connection network. */ setDefaultNetwork(network: Network | undefined): void { this.defaultNetwork = network; diff --git a/packages/appkit/src/core/network/walletkit.ts b/packages/appkit/src/core/network/walletkit.ts new file mode 100644 index 000000000..424d7e1ba --- /dev/null +++ b/packages/appkit/src/core/network/walletkit.ts @@ -0,0 +1,70 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +// Re-export of walletkit network primitives. Kept in a leaf file so internal +// modules (`./services/...`) can import without forming a cycle through `./index.ts`. + +/** + * Walletkit-side network manager that {@link AppKitNetworkManager} extends, adding default-network state and AppKit event emission. Apps usually interact with the {@link AppKitNetworkManager} subclass. + * + * @extract + * @public + * @category Class + * @section Networks + */ +export { KitNetworkManager } from '@ton/walletkit'; + +/** + * Indexer/RPC client interface used by AppKit to read on-chain state — balance, jettons, NFTs, etc. Each {@link Network} resolves to its own `ApiClient` via {@link AppKitNetworkManager}. Apps usually pull one through {@link getApiClient} rather than constructing it directly. + * + * @extract + * @public + * @category Type + * @section Client + */ +export { ApiClient } from '@ton/walletkit'; + +/** + * {@link ApiClient} implementation backed by the Toncenter API. + * + * @extract + * @public + * @category Class + * @section Client + */ +export { ApiClientToncenter } from '@ton/walletkit'; + +/** + * Configuration accepted by {@link ApiClientToncenter} — endpoint, API key, request timeout, custom `fetch`, target network, and optional DNS-resolver override. + * + * @extract + * @public + * @category Type + * @section Client + */ +export type { ApiClientToncenterConfig } from '@ton/walletkit'; + +/** + * {@link ApiClient} implementation backed by the TonAPI indexer. + * + * @extract + * @public + * @category Class + * @section Client + */ +export { ApiClientTonApi } from '@ton/walletkit'; + +/** + * Configuration shared by every {@link ApiClient} subclass — endpoint, API key, request timeout, custom `fetch`, target network and a `disableNetworkSend` dev toggle. Accepted directly by {@link ApiClientTonApi}; extended by {@link ApiClientToncenterConfig}. + * + * @extract + * @public + * @category Type + * @section Client + */ +export type { BaseApiClientConfig } from '@ton/walletkit'; diff --git a/packages/appkit/src/core/streaming/index.ts b/packages/appkit/src/core/streaming/index.ts index 3829c9b3f..bd6de1700 100644 --- a/packages/appkit/src/core/streaming/index.ts +++ b/packages/appkit/src/core/streaming/index.ts @@ -20,11 +20,57 @@ export type { StreamingAPI, TonCenterStreamingProviderConfig, TonApiStreamingProviderConfig, - BalanceUpdate, - TransactionsUpdate, - Transaction, - JettonUpdate, StreamingUpdate, StreamingWatchType, StreamingEvents, } from '@ton/walletkit'; + +/** + * Update payload delivered to {@link watchTransactions} / {@link watchTransactionsByAddress} subscribers when transactions land for the watched address. + * + * @extract + * @public + * @category Type + * @section Transactions + */ +export type { TransactionsUpdate } from '@ton/walletkit'; + +/** + * Single transaction record carried inside {@link TransactionsUpdate}'s `transactions` — account, lt/hash, in/out messages and emulation result. + * + * @extract + * @public + * @category Type + * @section Transactions + */ +export type { Transaction } from '@ton/walletkit'; + +/** + * Update payload delivered to {@link watchJettons} / {@link watchJettonsByAddress} subscribers when the watched owner's jetton balance changes. + * + * @extract + * @public + * @category Type + * @section Jettons + */ +export type { JettonUpdate } from '@ton/walletkit'; + +/** + * Finality stage carried by every streaming update — `'pending'` (in mempool), `'confirmed'` (included in a block), `'finalized'` (irreversible), or `'invalidated'` (rolled back). + * + * @extract + * @public + * @category Type + * @section Balances + */ +export type { StreamingUpdateStatus } from '@ton/walletkit'; + +/** + * Update payload delivered to {@link watchBalance} / {@link watchBalanceByAddress} subscribers when the watched address's TON balance changes. + * + * @extract + * @public + * @category Type + * @section Balances + */ +export type { BalanceUpdate } from '@ton/walletkit'; diff --git a/packages/appkit/src/core/wallets-manager/services/wallets-manager.ts b/packages/appkit/src/core/wallets-manager/services/wallets-manager.ts index 7d4765073..9b403f01d 100644 --- a/packages/appkit/src/core/wallets-manager/services/wallets-manager.ts +++ b/packages/appkit/src/core/wallets-manager/services/wallets-manager.ts @@ -25,21 +25,21 @@ export class WalletsManager { } /** - * All connected wallets + * All connected wallets. */ get wallets(): WalletInterface[] { return this._wallets; } /** - * Selected wallet id + * Selected wallet id. */ get selectedWalletId(): string | null { return this._selectedWalletId; } /** - * Selected wallet + * Selected wallet. */ get selectedWallet(): WalletInterface | null { if (!this._selectedWalletId) { @@ -50,15 +50,16 @@ export class WalletsManager { } /** - * Set selected wallet id + * Set selected wallet id. */ setSelectedWalletId(id: string | null): void { this._selectedWalletId = id; + this.emitter.emit(WALLETS_EVENTS.SELECTION_CHANGED, { walletId: this._selectedWalletId }, 'wallets-manager'); } /** * Set connected wallets - * Automatically handles selected wallet state + * Automatically handles selected wallet state. */ setWallets(wallets: WalletInterface[]): void { this._wallets = wallets; @@ -70,18 +71,12 @@ export class WalletsManager { // If list is not empty, auto-select the first one if (wallets.length > 0) { - this._selectedWalletId = wallets[0].getWalletId(); - this.emitter.emit( - WALLETS_EVENTS.SELECTION_CHANGED, - { walletId: this._selectedWalletId }, - 'wallets-manager', - ); + this.setSelectedWalletId(wallets[0].getWalletId()); return; } // Otherwise clear selection - this._selectedWalletId = null; - this.emitter.emit(WALLETS_EVENTS.SELECTION_CHANGED, { walletId: null }, 'wallets-manager'); + this.setSelectedWalletId(null); } } diff --git a/packages/appkit/src/crypto-onramp/index.ts b/packages/appkit/src/crypto-onramp/index.ts index 0660cbcc8..41df588ab 100644 --- a/packages/appkit/src/crypto-onramp/index.ts +++ b/packages/appkit/src/crypto-onramp/index.ts @@ -6,17 +6,81 @@ * */ -export { CryptoOnrampProvider, CryptoOnrampManager, CryptoOnrampError, CryptoOnrampErrorCode } from '@ton/walletkit'; +/** + * Error thrown by {@link CryptoOnrampManager} and crypto-onramp providers — extends {@link DefiError} with `name: 'CryptoOnrampError'` and a typed {@link CryptoOnrampErrorCode} on `code`. + * + * @extract + * @public + * @category Class + * @section Crypto Onramp + */ +export { CryptoOnrampError } from '@ton/walletkit'; + +/** + * Discriminator carried on every {@link CryptoOnrampError}'s `code` — covers provider/quote/deposit failures and refund-address validation. + * + * @extract + * @public + * @category Constants + * @section Crypto Onramp + */ +export { CryptoOnrampErrorCode } from '@ton/walletkit'; + +/** + * Abstract base class implemented by crypto-onramp providers (Layerswap, swaps.xyz, custom integrations). Apps don't use it directly — they consume providers through {@link CryptoOnrampManager} and the `getCryptoOnramp*` / {@link createCryptoOnrampDeposit} actions. + * + * @extract + * @public + * @category Class + * @section Crypto Onramp + */ +export { CryptoOnrampProvider } from '@ton/walletkit'; + +/** + * Runtime that owns registered {@link CryptoOnrampProvider}s and dispatches quote/deposit/status calls. Usually accessed through the higher-level actions ({@link getCryptoOnrampQuote}, {@link createCryptoOnrampDeposit}, {@link getCryptoOnrampStatus}). + * + * @extract + * @public + * @category Class + * @section Crypto Onramp + */ +export { CryptoOnrampManager } from '@ton/walletkit'; +/** + * @extract + * @public + * @category Type + * @section Crypto Onramp + */ export type { - CryptoOnrampAPI, - CryptoOnrampProviderInterface, - CryptoOnrampProviderMetadata, - CryptoOnrampProviderMetadataOverride, CryptoOnrampQuote, CryptoOnrampQuoteParams, CryptoOnrampDeposit, CryptoOnrampDepositParams, - CryptoOnrampStatus, - CryptoOnrampStatusParams, + CryptoOnrampProviderMetadata, + CryptoOnrampProviderMetadataOverride, + CryptoOnrampProviderInterface, } from '@ton/walletkit'; + +/** + * Final state of a crypto-onramp deposit returned by {@link getCryptoOnrampStatus} — `'success'` (delivered to the recipient), `'pending'` (still in flight), or `'failed'` (provider could not complete the deposit). + * + * @extract + * @public + * @category Type + * @section Crypto Onramp + */ +export type { CryptoOnrampStatus } from '@ton/walletkit'; + +/** + * Parameters accepted by {@link getCryptoOnrampStatus} — identifies a previously created deposit and the provider that issued it. + * + * @extract + * @public + * @category Type + * @section Crypto Onramp + */ +export type { CryptoOnrampStatusParams } from '@ton/walletkit'; + +// Internal-only — `CryptoOnrampAPI` is the contract `CryptoOnrampManager` satisfies, not consumed directly from `@ton/appkit`. +export type { CryptoOnrampAPI } from '@ton/walletkit'; diff --git a/packages/appkit/src/crypto-onramp/layerswap/index.ts b/packages/appkit/src/crypto-onramp/layerswap/index.ts index 8894baf33..a1d6eb65c 100644 --- a/packages/appkit/src/crypto-onramp/layerswap/index.ts +++ b/packages/appkit/src/crypto-onramp/layerswap/index.ts @@ -6,4 +6,56 @@ * */ -export * from '@ton/walletkit/crypto-onramp/layerswap'; +/** + * {@link CryptoOnrampProvider} implementation backed by Layerswap. Prefer the {@link createLayerswapProvider} factory over instantiating this class directly — the factory returns a `ProviderInput` ready to pass to {@link AppKitConfig}'s `providers` or {@link registerProvider}. + * + * @extract + * @public + * @category Class + * @section Crypto Onramp + */ +export { LayerswapCryptoOnrampProvider } from '@ton/walletkit/crypto-onramp/layerswap'; + +/** + * Build a Layerswap-backed {@link CryptoOnrampProvider} for AppKit. Pass the result to {@link AppKitConfig}'s `providers` or {@link registerProvider}. + * + * @extract + * @public + * @category Action + * @section Crypto Onramp + */ +export { createLayerswapProvider } from '@ton/walletkit/crypto-onramp/layerswap'; + +/** + * Configuration accepted by {@link createLayerswapProvider}. + * + * @extract + * @public + * @category Type + * @section Crypto Onramp + */ +export type { LayerswapProviderConfig } from '@ton/walletkit/crypto-onramp/layerswap'; + +/** + * Provider-specific metadata returned on a {@link CryptoOnrampQuote}'s `metadata` from Layerswap — carries the swap id and deposit action that {@link createCryptoOnrampDeposit} reads to build the deposit. + * + * @extract + * @public + * @category Type + * @section Crypto Onramp + */ +export type { LayerswapQuoteMetadata } from '@ton/walletkit/crypto-onramp/layerswap'; + +// Internal Layerswap response shapes — re-exported for compatibility but not surfaced in the documented reference. +export type { + LayerswapToken, + LayerswapNetwork, + LayerswapDepositAction, + LayerswapSwap, + LayerswapSwapStatus, + LayerswapQuote, + LayerswapSwapData, + LayerswapCreateSwapResponse, + LayerswapGetSwapResponse, + LayerswapErrorResponse, +} from '@ton/walletkit/crypto-onramp/layerswap'; diff --git a/packages/appkit/src/crypto-onramp/swaps-xyz/index.ts b/packages/appkit/src/crypto-onramp/swaps-xyz/index.ts index 85909caad..2133e978a 100644 --- a/packages/appkit/src/crypto-onramp/swaps-xyz/index.ts +++ b/packages/appkit/src/crypto-onramp/swaps-xyz/index.ts @@ -6,4 +6,63 @@ * */ -export * from '@ton/walletkit/crypto-onramp/swaps-xyz'; +/** + * {@link CryptoOnrampProvider} implementation backed by swaps.xyz. Prefer the {@link createSwapsXyzProvider} factory over instantiating this class directly — the factory returns a `ProviderInput` ready to pass to {@link AppKitConfig}'s `providers` or {@link registerProvider}. + * + * @extract + * @public + * @category Class + * @section Crypto Onramp + */ +export { SwapsXyzCryptoOnrampProvider } from '@ton/walletkit/crypto-onramp/swaps-xyz'; + +/** + * Build a swaps.xyz-backed {@link CryptoOnrampProvider} for AppKit. Pass the result to {@link AppKitConfig}'s `providers` or {@link registerProvider}. + * + * @extract + * @public + * @category Action + * @section Crypto Onramp + */ +export { createSwapsXyzProvider } from '@ton/walletkit/crypto-onramp/swaps-xyz'; + +/** + * Configuration accepted by {@link createSwapsXyzProvider}. + * + * @extract + * @public + * @category Type + * @section Crypto Onramp + */ +export type { SwapsXyzProviderConfig } from '@ton/walletkit/crypto-onramp/swaps-xyz'; + +/** + * swaps.xyz-specific options forwarded through `providerOptions` on {@link CryptoOnrampQuoteParams}. + * + * @extract + * @public + * @category Type + * @section Crypto Onramp + */ +export type { SwapsXyzQuoteOptions } from '@ton/walletkit/crypto-onramp/swaps-xyz'; + +/** + * Provider-specific metadata returned on a {@link CryptoOnrampQuote}'s `metadata` from swaps.xyz — carries the resolved action and bridge route that {@link createCryptoOnrampDeposit} needs. + * + * @extract + * @public + * @category Type + * @section Crypto Onramp + */ +export type { SwapsXyzQuoteMetadata } from '@ton/walletkit/crypto-onramp/swaps-xyz'; + +// Internal swaps.xyz response shapes — re-exported for compatibility but not surfaced in the documented reference. +export type { + SwapsXyzVmId, + SwapsXyzSwapDirection, + SwapsXyzPayment, + SwapsXyzEvmTx, + SwapsXyzBridgeRouteStep, + SwapsXyzGetActionResponse, + SwapsXyzErrorResponse, +} from '@ton/walletkit/crypto-onramp/swaps-xyz'; diff --git a/packages/appkit/src/index.ts b/packages/appkit/src/index.ts index 5026c5cff..06c1a439c 100644 --- a/packages/appkit/src/index.ts +++ b/packages/appkit/src/index.ts @@ -41,7 +41,6 @@ export * from './actions'; // Types export * from './types/connector'; -export * from './types/balance'; export * from './types/wallet'; export * from './types/query'; export * from './types/utils'; @@ -51,6 +50,8 @@ export * from './types/nft'; export * from './types/transaction'; export * from './types/primitives'; export * from './types/signing'; +export * from './types/provider'; +export * from './types/client'; // Utils export * from './utils'; diff --git a/packages/appkit/src/onramp/index.ts b/packages/appkit/src/onramp/index.ts index bed681716..b5654e95e 100644 --- a/packages/appkit/src/onramp/index.ts +++ b/packages/appkit/src/onramp/index.ts @@ -6,6 +6,10 @@ * */ +// Internal-only re-exports (used by appkit code; not yet part of the public API). +export { OnrampManager } from '@ton/walletkit'; +export type { OnrampProviderInterface, OnrampParams, OnrampQuote, OnrampQuoteParams } from '@ton/walletkit'; + // fiat-onramp: not ready — exported via sub-path to keep off main @ton/appkit API export { getOnrampProvider, diff --git a/packages/appkit/src/queries/index.ts b/packages/appkit/src/queries/index.ts index f3a487a3f..acad46aac 100644 --- a/packages/appkit/src/queries/index.ts +++ b/packages/appkit/src/queries/index.ts @@ -37,7 +37,7 @@ export { type DisconnectVariables, } from './connectors/disconnect'; -// Crypto onramp +// Crypto Onramp export { getCryptoOnrampQuoteQueryOptions, type GetCryptoOnrampQuoteQueryConfig, diff --git a/packages/appkit/src/queries/jettons/get-jetton-balance-by-address.ts b/packages/appkit/src/queries/jettons/get-jetton-balance-by-address.ts index a42ce0555..f173386da 100644 --- a/packages/appkit/src/queries/jettons/get-jetton-balance-by-address.ts +++ b/packages/appkit/src/queries/jettons/get-jetton-balance-by-address.ts @@ -7,9 +7,9 @@ */ import type { QueryClient } from '@tanstack/query-core'; -import type { TokenAmount } from '@ton/walletkit'; import type { AppKit } from '../../core/app-kit'; +import type { TokenAmount } from '../../types/primitives'; import { getJettonBalance } from '../../actions/jettons/get-jetton-balance'; import type { GetJettonBalanceOptions as GetJettonBalanceParameters } from '../../actions/jettons/get-jetton-balance'; import type { QueryOptions, QueryParameter } from '../../types/query'; diff --git a/packages/appkit/src/queries/jettons/get-jetton-wallet-address.ts b/packages/appkit/src/queries/jettons/get-jetton-wallet-address.ts index 1881825e1..01cc191f6 100644 --- a/packages/appkit/src/queries/jettons/get-jetton-wallet-address.ts +++ b/packages/appkit/src/queries/jettons/get-jetton-wallet-address.ts @@ -6,9 +6,8 @@ * */ -import type { UserFriendlyAddress } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { UserFriendlyAddress } from '../../types/primitives'; import { getJettonWalletAddress } from '../../actions/jettons/get-jetton-wallet-address'; import type { GetJettonWalletAddressOptions as GetJettonWalletAddressParameters } from '../../actions/jettons/get-jetton-wallet-address'; import type { QueryOptions, QueryParameter } from '../../types/query'; diff --git a/packages/appkit/src/queries/nft/get-nft.ts b/packages/appkit/src/queries/nft/get-nft.ts index 4d6175b90..53a7e7d3b 100644 --- a/packages/appkit/src/queries/nft/get-nft.ts +++ b/packages/appkit/src/queries/nft/get-nft.ts @@ -6,9 +6,8 @@ * */ -import type { NFT } from '@ton/walletkit'; - import type { AppKit } from '../../core/app-kit'; +import type { NFT } from '../../types/nft'; import { getNft } from '../../actions/nft/get-nft'; import type { GetNftOptions as GetNftParameters } from '../../actions/nft/get-nft'; import type { QueryOptions, QueryParameter } from '../../types/query'; diff --git a/packages/appkit/src/staking/index.ts b/packages/appkit/src/staking/index.ts index 4008f03cf..805fa68b9 100644 --- a/packages/appkit/src/staking/index.ts +++ b/packages/appkit/src/staking/index.ts @@ -6,15 +6,64 @@ * */ -export { - DefiError, - StakingProvider, - UnstakeMode, - StakingError, - StakingErrorCode, - StakingManager, -} from '@ton/walletkit'; +// `DefiError` is shared by swap and staking; it is exported via `./swap` to keep a single declaration. + +/** + * Abstract base class implemented by staking providers (Tonstakers, custom integrations, …). Apps don't use it directly — they consume providers through {@link StakingManager} and the `getStaking*` / `buildStakeTransaction` actions. + * + * @extract + * @public + * @category Class + * @section Staking + */ +export { StakingProvider } from '@ton/walletkit'; + +/** + * Error thrown by {@link StakingManager} and staking providers — extends {@link DefiError} with `name: 'StakingError'` and a typed {@link StakingErrorCode} on `code`. + * + * @extract + * @public + * @category Class + * @section Staking + */ +export { StakingError } from '@ton/walletkit'; + +/** + * Runtime that owns registered {@link StakingProvider}s and dispatches quote/stake/balance calls. Usually accessed through the higher-level actions ({@link getStakingQuote}, {@link buildStakeTransaction}, {@link getStakedBalance}). + * + * @extract + * @public + * @category Class + * @section Staking + */ +export { StakingManager } from '@ton/walletkit'; + +/** + * Discriminator carried on every {@link StakingError}'s `code` — `'INVALID_PARAMS'` (the request was malformed) or `'UNSUPPORTED_OPERATION'` (the provider doesn't support this call). + * + * @extract + * @public + * @category Constants + * @section Staking + */ +export { StakingErrorCode } from '@ton/walletkit'; + +/** + * Allowed unstake-timing flavours referenced by {@link UnstakeModes} and {@link StakingProviderMetadata}'s `supportedUnstakeModes` — `'INSTANT'` (immediate withdrawal when the pool has liquidity, otherwise the funds are returned), `'WHEN_AVAILABLE'` (paid out as soon as liquidity is available — instantly or at round end), `'ROUND_END'` (paid out at the end of the staking round, typically for the best rate). + * + * @extract + * @public + * @category Constants + * @section Staking + */ +export { UnstakeMode } from '@ton/walletkit'; +/** + * @extract + * @public + * @category Type + * @section Staking + */ export type { UnstakeModes, StakeParams, @@ -23,8 +72,20 @@ export type { StakingQuoteParams, StakingBalance, StakingProviderInfo, - StakingProviderInterface, StakingQuoteDirection, StakingProviderMetadata, - StakingTokenInfo, + StakingProviderMetadataOverride, } from '@ton/walletkit'; + +/** + * Display metadata for a staking-pool token — `ticker`, `decimals` and `address` (or `'ton'` for native TON). Carried on {@link StakingProviderMetadata}'s `stakeToken` and `receiveToken` so the UI can render the pool's input/output assets. + * + * @extract + * @public + * @category Type + * @section Staking + */ +export type { StakingTokenInfo } from '@ton/walletkit'; + +// Internal-only — `StakingProviderInterface` is the contract authors implement, not consumed from `@ton/appkit`. +export type { StakingProviderInterface } from '@ton/walletkit'; diff --git a/packages/appkit/src/staking/tonstakers/index.ts b/packages/appkit/src/staking/tonstakers/index.ts index 9b56f3973..e5781ee7d 100644 --- a/packages/appkit/src/staking/tonstakers/index.ts +++ b/packages/appkit/src/staking/tonstakers/index.ts @@ -6,4 +6,42 @@ * */ -export * from '@ton/walletkit/staking/tonstakers'; +/** + * {@link StakingProvider} implementation backed by Tonstakers. The constructor is private — always go through the {@link createTonstakersProvider} factory and pass the result to {@link AppKitConfig}'s `providers` or {@link registerProvider}. + * + * @extract + * @public + * @category Class + * @section Staking + */ +export { TonStakersStakingProvider } from '@ton/walletkit/staking/tonstakers'; + +/** + * Build a Tonstakers-backed {@link StakingProvider} for AppKit. Pass the result to {@link AppKitConfig}'s `providers` or {@link registerProvider}. + * + * @extract + * @public + * @category Action + * @section Staking + */ +export { createTonstakersProvider } from '@ton/walletkit/staking/tonstakers'; + +/** + * Configuration accepted by {@link createTonstakersProvider} — map of chain ID (e.g. `Network.mainnet().chainId`) to its per-chain {@link TonStakersChainConfig}. + * + * @extract + * @public + * @category Type + * @section Staking + */ +export type { TonStakersProviderConfig } from '@ton/walletkit/staking/tonstakers'; + +/** + * Per-chain Tonstakers config — optional TonAPI key for APY reads and an optional staking-provider metadata override. + * + * @extract + * @public + * @category Type + * @section Staking + */ +export type { TonStakersChainConfig } from '@ton/walletkit/staking/tonstakers'; diff --git a/packages/appkit/src/swap/dedust/index.ts b/packages/appkit/src/swap/dedust/index.ts index 46f0da4f8..3fa2a7e44 100644 --- a/packages/appkit/src/swap/dedust/index.ts +++ b/packages/appkit/src/swap/dedust/index.ts @@ -6,4 +6,71 @@ * */ -export * from '@ton/walletkit/swap/dedust'; +/** + * {@link SwapProvider} implementation backed by DeDust. Prefer the {@link createDeDustProvider} factory over instantiating this class directly — the factory returns a `ProviderInput` ready to pass to {@link AppKitConfig}'s `providers` or {@link registerProvider}. + * + * @extract + * @public + * @category Class + * @section Swap + */ +export { DeDustSwapProvider } from '@ton/walletkit/swap/dedust'; + +/** + * Build a DeDust-backed {@link SwapProvider} for AppKit. Pass the result to {@link AppKitConfig}'s `providers` or {@link registerProvider}. + * + * @extract + * @public + * @category Action + * @section Swap + */ +export { createDeDustProvider } from '@ton/walletkit/swap/dedust'; + +/** + * Configuration accepted by {@link createDeDustProvider}. + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { DeDustSwapProviderConfig } from '@ton/walletkit/swap/dedust'; + +/** + * DeDust-specific options forwarded through `providerOptions` on {@link SwapQuoteParams} / {@link SwapParams}. + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { DeDustProviderOptions } from '@ton/walletkit/swap/dedust'; + +/** + * Optional referral metadata attached to DeDust swaps so the provider can attribute them. + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { DeDustReferralOptions } from '@ton/walletkit/swap/dedust'; + +/** + * Provider-specific metadata returned on a {@link SwapQuote}'s `metadata` from DeDust — carries the resolved route, fees and `swapData` payload that {@link buildSwapTransaction} needs. + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { DeDustQuoteMetadata } from '@ton/walletkit/swap/dedust'; + +// Internal — type guard for DeDust quote metadata + walletkit response shapes; re-exported for compatibility but not surfaced in the documented reference. +export { isDeDustQuoteMetadata } from '@ton/walletkit/swap/dedust'; +export type { + DeDustQuoteResponse, + DeDustRouteStep, + DeDustSwapData, + DeDustSwapResponse, +} from '@ton/walletkit/swap/dedust'; diff --git a/packages/appkit/src/swap/index.ts b/packages/appkit/src/swap/index.ts index 5b20d19f1..7b75b0f08 100644 --- a/packages/appkit/src/swap/index.ts +++ b/packages/appkit/src/swap/index.ts @@ -6,15 +6,145 @@ * */ -export { DefiError, DefiErrorCode, SwapError, SwapErrorCode, SwapProvider, SwapManager } from '@ton/walletkit'; - -export type { - SwapToken, - TokenAmount, - SwapParams, - SwapAPI, - SwapQuote, - SwapQuoteParams, - DefiManagerAPI, - DefiProvider, -} from '@ton/walletkit'; +/** + * Base error thrown across all DeFi domains (swap, staking, onramp, crypto-onramp). Subclassed by {@link SwapError}, {@link StakingError}, {@link CryptoOnrampError} and the internal onramp error — catch the base when you don't care which domain produced the failure. + * + * @extract + * @public + * @category Class + * @section DeFi + */ +export { DefiError } from '@ton/walletkit'; + +/** + * Discriminator carried on {@link DefiError}'s `code` for codes shared by every DeFi domain — provider lookup, default-provider state, and shared transport/validation failures. Subclass codes ({@link SwapErrorCode}, {@link StakingErrorCode}, {@link CryptoOnrampErrorCode}) cover domain-specific failures. + * + * @extract + * @public + * @category Constants + * @section DeFi + */ +export { DefiErrorCode } from '@ton/walletkit'; + +/** + * Error thrown by {@link SwapManager} and swap providers — extends {@link DefiError} with `name: 'SwapError'` and a typed {@link SwapErrorCode} on `code`. + * + * @extract + * @public + * @category Class + * @section Swap + */ +export { SwapError } from '@ton/walletkit'; + +/** + * Discriminator carried on every {@link SwapError}'s `code` — covers quote / liquidity / transaction-build failures plus the shared `NETWORK_ERROR` for upstream-API faults. + * + * @extract + * @public + * @category Constants + * @section Swap + */ +export { SwapErrorCode } from '@ton/walletkit'; + +/** + * Abstract base class implemented by swap providers (DeDust, Omniston, custom integrations). Apps don't use it directly — they consume providers through {@link SwapManager} and the `getSwap*` / `buildSwapTransaction` actions. + * + * @extract + * @public + * @category Class + * @section Swap + */ +export { SwapProvider } from '@ton/walletkit'; + +/** + * Runtime that owns registered {@link SwapProvider}s and dispatches quote/swap calls. Usually accessed through the higher-level actions ({@link getSwapQuote}, {@link buildSwapTransaction}). + * + * @extract + * @public + * @category Class + * @section Swap + */ +export { SwapManager } from '@ton/walletkit'; + +/** + * Shape every DeFi domain manager (swap, staking, onramp, crypto-onramp) satisfies — provider registration, default-provider selection and lookups. Mostly relevant when authoring a new domain manager. + * + * @extract + * @public + * @category Type + * @section DeFi + */ +export type { DefiManagerAPI } from '@ton/walletkit'; + +/** + * Base interface implemented by every DeFi provider (swap, staking, onramp, crypto-onramp) — exposes `providerId`, `type` and `getSupportedNetworks`. Domain-specific provider interfaces extend this with quote/build/status methods. + * + * @extract + * @public + * @category Type + * @section DeFi + */ +export type { DefiProvider } from '@ton/walletkit'; + +/** + * Discriminator that tags every {@link DefiProvider} with its kind — `'swap'`, `'staking'`, `'onramp'`, or `'crypto-onramp'`. Used by {@link registerProvider} to dispatch to the right manager. + * + * @extract + * @public + * @category Type + * @section DeFi + */ +export type { DefiProviderType } from '@ton/walletkit'; + +/** + * Token descriptor passed to {@link getSwapQuote} via {@link SwapQuoteParams}'s `from` and `to` fields (and surfaced on the resulting {@link SwapQuote}) — address, decimals plus optional symbol/name/image used by swap-input UIs. + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { SwapToken } from '@ton/walletkit'; + +/** + * Parameters consumed by {@link buildSwapTransaction} — the previously obtained {@link SwapQuote} plus optional provider-specific options (`TProviderOptions`). + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { SwapParams } from '@ton/walletkit'; + +/** + * API surface exposed by {@link SwapManager} — quote and build-transaction calls (plus the provider-management methods inherited from {@link DefiManagerAPI}). Mostly relevant when authoring a swap manager replacement. + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { SwapAPI } from '@ton/walletkit'; + +/** + * Quote returned by {@link getSwapQuote} — source/target tokens, expected amounts, rate, slippage, fees and the provider-specific `metadata` that {@link buildSwapTransaction} needs to construct the transaction. + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { SwapQuote } from '@ton/walletkit'; + +/** + * Parameters consumed by {@link getSwapQuote} — source/target tokens and an amount that is interpreted as either the spend side or the receive side (`isReverseSwap` flag), plus optional slippage and provider-specific options. + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { SwapQuoteParams } from '@ton/walletkit'; + +// Internal-only — `SwapProviderInterface` is the contract authors implement, not consumed from `@ton/appkit`. +export type { SwapProviderInterface } from '@ton/walletkit'; diff --git a/packages/appkit/src/swap/omniston/index.ts b/packages/appkit/src/swap/omniston/index.ts index c623c0c9c..e3cbd344a 100644 --- a/packages/appkit/src/swap/omniston/index.ts +++ b/packages/appkit/src/swap/omniston/index.ts @@ -6,4 +6,62 @@ * */ -export * from '@ton/walletkit/swap/omniston'; +/** + * {@link SwapProvider} implementation backed by Omniston. Prefer the {@link createOmnistonProvider} factory over instantiating this class directly — the factory returns a `ProviderInput` ready to pass to {@link AppKitConfig}'s `providers` or {@link registerProvider}. + * + * @extract + * @public + * @category Class + * @section Swap + */ +export { OmnistonSwapProvider } from '@ton/walletkit/swap/omniston'; + +/** + * Build an Omniston-backed {@link SwapProvider} for AppKit. Pass the result to {@link AppKitConfig}'s `providers` or {@link registerProvider}. + * + * @extract + * @public + * @category Action + * @section Swap + */ +export { createOmnistonProvider } from '@ton/walletkit/swap/omniston'; + +/** + * Configuration accepted by {@link createOmnistonProvider}. + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { OmnistonSwapProviderConfig } from '@ton/walletkit/swap/omniston'; + +/** + * Omniston-specific options forwarded through `providerOptions` on {@link SwapQuoteParams} / {@link SwapParams}. + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { OmnistonProviderOptions } from '@ton/walletkit/swap/omniston'; + +/** + * Optional referrer metadata attached to Omniston swaps so the provider can attribute them. + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { OmnistonReferrerOptions } from '@ton/walletkit/swap/omniston'; + +/** + * Provider-specific metadata returned on a {@link SwapQuote}'s `metadata` from Omniston — carries the resolved route and signed quote payload that {@link buildSwapTransaction} needs. + * + * @extract + * @public + * @category Type + * @section Swap + */ +export type { OmnistonQuoteMetadata } from '@ton/walletkit/swap/omniston'; diff --git a/packages/appkit/src/types/balance.ts b/packages/appkit/src/types/api-client.ts similarity index 65% rename from packages/appkit/src/types/balance.ts rename to packages/appkit/src/types/api-client.ts index 27f18d1ab..a14dab9d0 100644 --- a/packages/appkit/src/types/balance.ts +++ b/packages/appkit/src/types/api-client.ts @@ -6,6 +6,4 @@ * */ -import type { TokenAmount } from '@ton/walletkit'; - -export type Balance = TokenAmount; +export { ApiClient } from '@ton/walletkit'; diff --git a/packages/appkit/src/types/client.ts b/packages/appkit/src/types/client.ts new file mode 100644 index 000000000..88f67a3dc --- /dev/null +++ b/packages/appkit/src/types/client.ts @@ -0,0 +1,37 @@ +/** + * Copyright (c) TonTech. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +/** + * Display metadata for a token (TON, jetton, or NFT) — name, symbol, image and animation as reported by the indexer. Surfaced as {@link Jetton}'s `info` and {@link NFT}'s `info`. + * + * @extract + * @public + * @category Type + * @section Client + */ +export type { TokenInfo } from '@ton/walletkit'; + +/** + * Map of raw addresses to their resolved metadata, returned alongside indexed lists (e.g. {@link JettonsResponse}, {@link NFTsResponse}) so consumers can render labels without extra lookups. + * + * @extract + * @public + * @category Type + * @section Client + */ +export type { AddressBook } from '@ton/walletkit'; + +/** + * Single entry inside an {@link AddressBook} — pairs the user-friendly address with optional domain name and the list of contract interfaces it implements. + * + * @extract + * @public + * @category Type + * @section Client + */ +export type { AddressBookEntry } from '@ton/walletkit'; diff --git a/packages/appkit/src/types/connector.ts b/packages/appkit/src/types/connector.ts index 834cf92a0..078544a0f 100644 --- a/packages/appkit/src/types/connector.ts +++ b/packages/appkit/src/types/connector.ts @@ -12,51 +12,91 @@ import type { AppKitNetworkManager } from '../core/network'; import type { Network } from './network'; /** - * Interface for wallet connectors + * Wallet connector contract — the protocol-specific bridge (TonConnect, embedded wallet, …) AppKit drives once you register it via {@link AppKitConfig}'s `connectors`. + * + * @public + * @category Type + * @section Connectors */ export interface Connector { - /** Provider unique identifier */ + /** Stable connector identifier, unique within an AppKit instance. */ readonly id: string; - /** Protocol type (e.g. 'tonconnect') */ + /** Protocol type (e.g. `'tonconnect'`). Multiple connectors can share the same type. */ readonly type: string; + /** Display metadata (name, icon) shown in connect UIs. */ readonly metadata: ConnectorMetadata; - /** Cleanup connector resources */ + /** Release any resources held by the connector. Call on app teardown. */ destroy(): void; - /** Connect a wallet */ + /** Initiate a wallet connection flow on the given network. */ connectWallet(network?: Network): Promise; - /** Disconnect a wallet */ + /** Disconnect the currently connected wallet, if any. */ disconnectWallet(): Promise; - /** Get connected wallets */ + /** Wallets currently connected through this connector. */ getConnectedWallets(): WalletInterface[]; } +/** + * Display metadata for a {@link Connector}, surfaced in connect UIs to help users pick the right wallet. + * + * @public + * @category Type + * @section Connectors + */ export interface ConnectorMetadata { + /** Human-readable connector name (e.g., `'TonConnect'`). */ name: string; + /** Optional URL of an icon shown next to the name. */ iconUrl?: string; } /** - * Context passed to connector factory functions. + * Context that AppKit injects into a {@link ConnectorFactory} when building the connector at registration time. + * + * @public + * @category Type + * @section Connectors */ export interface ConnectorFactoryContext { + /** Network manager the connector should use for client lookups and default-network reads. */ networkManager: AppKitNetworkManager; + /** Event emitter the connector should publish wallet/connection events to. */ eventEmitter: AppKitEmitter; - ssr?: boolean; } -/** Factory function that creates a connector from context */ +/** + * Factory that builds a {@link Connector} from {@link ConnectorFactoryContext}. AppKit calls it at registration time. + * + * @public + * @category Type + * @section Connectors + */ export type ConnectorFactory = (ctx: ConnectorFactoryContext) => Connector; -/** A connector instance or a factory that creates one */ +/** + * Either a ready-made {@link Connector} or a {@link ConnectorFactory} that produces one — the value accepted by {@link addConnector} and {@link AppKitConfig}'s `connectors`. + * + * @public + * @category Type + * @section Connectors + */ export type ConnectorInput = Connector | ConnectorFactory; -/** Helper for creating typed connector factories */ +/** + * Identity helper for typing a {@link ConnectorFactory} inline — returns the factory unchanged so authors get parameter inference without spelling the type out. + * + * @param factory - {@link ConnectorFactory} Factory to wrap. + * @returns The same factory, typed as {@link ConnectorFactory}. + * + * @public + * @category Action + * @section Connectors + */ export const createConnector = (factory: ConnectorFactory): ConnectorFactory => { return factory; }; diff --git a/packages/appkit/src/types/jetton.ts b/packages/appkit/src/types/jetton.ts index ed0191fa1..bb28a5984 100644 --- a/packages/appkit/src/types/jetton.ts +++ b/packages/appkit/src/types/jetton.ts @@ -6,4 +6,42 @@ * */ -export type { Jetton, JettonInfo } from '@ton/walletkit'; +/** + * Fungible TEP-74 token held in the user's TON wallet — carries the master contract address, the user's jetton-wallet address, current balance, and token metadata. + * + * @extract + * @public + * @category Type + * @section Jettons + */ +export type { Jetton } from '@ton/walletkit'; + +/** + * Token metadata for a jetton master — name, symbol, decimals, image, and verification status as reported by the indexer. + * + * @extract + * @public + * @category Type + * @section Jettons + */ +export type { JettonInfo } from '@ton/walletkit'; + +/** + * Response payload of {@link getJettons} / {@link getJettonsByAddress} — the list of {@link Jetton}s plus the address book that resolves raw addresses inside it. + * + * @extract + * @public + * @category Type + * @section Jettons + */ +export type { JettonsResponse } from '@ton/walletkit'; + +/** + * Verification metadata reported by the indexer for a {@link JettonInfo} — `verified` flag plus optional verifier source. + * + * @extract + * @public + * @category Type + * @section Jettons + */ +export type { JettonVerification } from '@ton/walletkit'; diff --git a/packages/appkit/src/types/network.ts b/packages/appkit/src/types/network.ts index 006b43054..1e190460c 100644 --- a/packages/appkit/src/types/network.ts +++ b/packages/appkit/src/types/network.ts @@ -6,4 +6,30 @@ * */ -export { Network } from '@ton/walletkit'; +/** + * @extract + * @public + * @category Type + * @section Networks + */ +export { Network, NetworkAdapters, NetworkConfig } from '@ton/walletkit'; + +/** + * Configuration accepted by {@link NetworkConfig}'s `apiClient` — picks an {@link ApiClient} implementation (Toncenter / TonAPI) and supplies its endpoint URL plus optional API key. + * + * @extract + * @public + * @category Type + * @section Client + */ +export { ApiClientConfig } from '@ton/walletkit'; + +/** + * Walletkit-side options shape consumed by {@link KitNetworkManager}'s constructor — chiefly the `networks` map keyed by chain ID. {@link AppKit} constructs the manager for you, so apps rarely instantiate this directly. + * + * @extract + * @public + * @category Type + * @section Networks + */ +export type { TonWalletKitOptions } from '@ton/walletkit'; diff --git a/packages/appkit/src/types/nft.ts b/packages/appkit/src/types/nft.ts index dd057ba05..a147728a3 100644 --- a/packages/appkit/src/types/nft.ts +++ b/packages/appkit/src/types/nft.ts @@ -6,4 +6,42 @@ * */ +/** + * Non-fungible TEP-62 token held in the user's TON wallet — carries the contract address, optional collection link, owner, sale state, and on-chain metadata. + * + * @extract + * @public + * @category Type + * @section NFTs + */ export type { NFT } from '@ton/walletkit'; + +/** + * Response payload of {@link getNfts} / {@link getNftsByAddress} — the list of {@link NFT}s plus an address book that resolves raw addresses inside it. + * + * @extract + * @public + * @category Type + * @section NFTs + */ +export type { NFTsResponse } from '@ton/walletkit'; + +/** + * Single trait of an {@link NFT} — `traitType` names the category (e.g., `"Background"`), `value` carries the trait's value (e.g., `"Blue"`). + * + * @extract + * @public + * @category Type + * @section NFTs + */ +export type { NFTAttribute } from '@ton/walletkit'; + +/** + * NFT collection (TEP-62) — surfaced as {@link NFT}'s `collection` and carries the collection's name, image, owner and minting cursor. + * + * @extract + * @public + * @category Type + * @section NFTs + */ +export type { NFTCollection } from '@ton/walletkit'; diff --git a/packages/appkit/src/types/primitives.ts b/packages/appkit/src/types/primitives.ts index 62317acb4..a2c4fdbdf 100644 --- a/packages/appkit/src/types/primitives.ts +++ b/packages/appkit/src/types/primitives.ts @@ -6,4 +6,52 @@ * */ +/** + * Map of extra-currency ids to raw amounts attached to a transaction message — TON's mechanism for transferring non-jetton native tokens (e.g., wrapped or testnet currencies). Keys are the extra-currency ids defined by the masterchain configuration. + * + * @extract + * @public + * @category Type + * @section Primitives + */ +export type { ExtraCurrencies } from '@ton/walletkit'; + +/** + * Base64-encoded byte string — used for transaction payloads, BoCs, signatures, and other opaque binary blobs that travel through TonConnect and the indexer APIs. + * + * @extract + * @public + * @category Type + * @section Primitives + */ export type { Base64String } from '@ton/walletkit'; + +/** + * `0x`-prefixed hexadecimal string used for public keys and other hashes. + * + * @extract + * @public + * @category Type + * @section Primitives + */ +export type { Hex } from '@ton/walletkit'; + +/** + * Decimal string carrying a token amount. Preserves precision and avoids floating-point rounding (e.g., `"1.5"` TON, or raw nano units depending on the API). + * + * @extract + * @public + * @category Type + * @section Primitives + */ +export type { TokenAmount } from '@ton/walletkit'; + +/** + * User-friendly TON wallet address as a base64url string (e.g., `"EQDtFp...4q2"`). + * + * @extract + * @public + * @category Type + * @section Primitives + */ +export type { UserFriendlyAddress } from '@ton/walletkit'; diff --git a/packages/appkit/src/types/provider.ts b/packages/appkit/src/types/provider.ts index 51d5748df..4851ad798 100644 --- a/packages/appkit/src/types/provider.ts +++ b/packages/appkit/src/types/provider.ts @@ -6,9 +6,30 @@ * */ -import type { SwapProviderInterface, StakingProviderInterface } from '@ton/walletkit'; +import type { SwapProviderInterface } from '../swap'; +import type { StakingProviderInterface } from '../staking'; /** - * Provider configuration + * Internal union of registerable DeFi provider instances (swap or staking) — used to type provider-related collections inside AppKit. */ export type Provider = SwapProviderInterface | StakingProviderInterface; + +/** + * Either a ready-made DeFi/onramp provider instance or a factory that produces one — the value accepted by {@link AppKitConfig}'s `providers` and {@link registerProvider}. + * + * @extract + * @public + * @category Type + * @section DeFi + */ +export type { ProviderInput } from '@ton/walletkit'; + +/** + * Context that AppKit's DeFi managers inject into a {@link ProviderInput} factory at registration time — gives the provider access to AppKit's network manager and event emitter. + * + * @extract + * @public + * @category Type + * @section DeFi + */ +export type { ProviderFactoryContext } from '@ton/walletkit'; diff --git a/packages/appkit/src/types/query.ts b/packages/appkit/src/types/query.ts index 1ce879206..a43ac30ac 100644 --- a/packages/appkit/src/types/query.ts +++ b/packages/appkit/src/types/query.ts @@ -10,22 +10,51 @@ import type * as Query from '@tanstack/query-core'; import type { Compute, LooseOmit, RequiredBy, UnionLooseOmit } from './utils.js'; +/** + * TanStack Query `useMutation` options forwarded by AppKit's `use*Mutation` hooks via `parameters.mutation` — `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper and stripped from this shape. + * + * @public + * @category Type + * @section Primitives + */ +export type MutationOptionsOverride = LooseOmit< + Query.MutationOptions, context>, + 'mutationFn' | 'mutationKey' | 'throwOnError' +>; + export type MutationParameter = { - mutation?: - | LooseOmit< - Query.MutationOptions, context>, - 'mutationFn' | 'mutationKey' | 'throwOnError' - > - | undefined; + /** + * TanStack Query mutation options forwarded to `useMutation` (`onSuccess`, `onError`, `onMutate`, `retry`, …). `mutationFn`, `mutationKey` and `throwOnError` are managed by the wrapper. + * @typeAs MutationOptionsOverride + */ + mutation?: MutationOptionsOverride | undefined; }; +/** + * TanStack Query `useQuery` options forwarded by AppKit's `use*Query` hooks via `parameters.query` — `queryKey` and `queryFn` are managed by the wrapper and stripped from this shape. + * + * @public + * @category Type + * @section Primitives + */ +export type QueryOptionsOverride< + queryFnData = unknown, + error = Query.DefaultError, + data = queryFnData, + queryKey extends Query.QueryKey = Query.QueryKey, +> = UnionLooseOmit, 'queryKey' | 'queryFn'>; + export type QueryParameter< queryFnData = unknown, error = Query.DefaultError, data = queryFnData, queryKey extends Query.QueryKey = Query.QueryKey, > = { - query?: UnionLooseOmit, 'queryKey' | 'queryFn'> | undefined; + /** + * TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. + * @typeAs QueryOptionsOverride + */ + query?: QueryOptionsOverride | undefined; }; export type QueryOptions< diff --git a/packages/appkit/src/types/signing.ts b/packages/appkit/src/types/signing.ts index c97fc2403..c1cd951e7 100644 --- a/packages/appkit/src/types/signing.ts +++ b/packages/appkit/src/types/signing.ts @@ -12,7 +12,11 @@ import type { Base64String } from './primitives'; // SignData types for wallet adapter /** - * Data to be signed by the wallet, discriminated by type. + * Payload the user is asked to sign — discriminated union over `'text'`, `'binary'`, and `'cell'`. Nested under {@link SignDataRequest}'s `data`. + * + * @public + * @category Type + * @section Signing */ export type SignData = | { type: 'text'; value: SignDataText } @@ -20,59 +24,75 @@ export type SignData = | { type: 'cell'; value: SignDataCell }; /** - * Binary data to be signed. + * Binary variant of {@link SignData} — opaque byte content the user is asked to sign. + * + * @public + * @category Type + * @section Signing */ export interface SignDataBinary { - /** - * Raw binary content encoded as bytes in Base64 - */ + /** Raw binary content encoded as Base64. */ content: Base64String; } /** - * TON Cell data to be signed with a schema definition. + * TON cell variant of {@link SignData} — Base64-encoded cell payload paired with the schema needed to parse it. + * + * @public + * @category Type + * @section Signing */ export interface SignDataCell { - /** - * Schema describing the cell structure for parsing - */ + /** TL-B-style schema describing the cell layout so the wallet can render the payload to the user. */ schema: string; - /** - * Cell content encoded in Base64 - */ + /** Cell content encoded as Base64. */ content: Base64String; } /** - * Plain text data to be signed. + * Plain-text variant of {@link SignData} — UTF-8 string the user is asked to sign. + * + * @public + * @category Type + * @section Signing */ export interface SignDataText { - /** - * Text content to be signed - */ + /** UTF-8 text the user signs. */ content: string; } -/** SignData Request Payload - sent to wallet */ +/** + * Sign-data payload sent to {@link WalletInterface}'s `signData` — discriminated by `data.type` (`'text'`, `'binary'`, or `'cell'`). + * + * @public + * @category Type + * @section Signing + */ export interface SignDataRequest { - /** Network */ + /** Network to issue the sign request against. Defaults to the wallet's current network. */ network?: Network; - /** Sender address in raw format */ + /** Sender address in raw format. Usually omitted, the wallet fills it in. */ from?: string; - /** Data to sign */ + /** Payload the user is asked to sign. */ data: SignData; } -/** SignData Response - returned from wallet */ +/** + * Wallet response to a {@link SignDataRequest} — carries the signature plus the canonicalized address, timestamp, and domain the wallet committed to. + * + * @public + * @category Type + * @section Signing + */ export interface SignDataResponse { - /** Base64 encoded signature */ + /** Base64-encoded signature. */ signature: string; - /** Wallet address that signed */ + /** Wallet address that signed, in user-friendly format. */ address: string; - /** Unix timestamp when signed */ + /** Unix timestamp the wallet stamped onto the signature. */ timestamp: number; - /** Domain of the dApp */ + /** dApp domain the wallet bound the signature to. */ domain: string; - /** Original payload that was signed */ + /** Original payload that was signed, echoed back for binding. */ payload: SignDataRequest; } diff --git a/packages/appkit/src/types/transaction.ts b/packages/appkit/src/types/transaction.ts index 0255b717b..783389679 100644 --- a/packages/appkit/src/types/transaction.ts +++ b/packages/appkit/src/types/transaction.ts @@ -6,60 +6,62 @@ * */ -import type { ExtraCurrencies, TokenAmount } from '@ton/walletkit'; - +import type { ExtraCurrencies, TokenAmount } from './primitives'; import type { Network } from './network'; -export type { TransactionStatus } from '@ton/walletkit'; +export type { TransactionStatus, TransactionStatusResponse } from '@ton/walletkit'; + +/** + * Wallet response carrying the BoC (bag of cells) of the external message that was signed and broadcast — used to track or hash the resulting transaction. + * + * @extract + * @public + * @category Type + * @section Transactions + */ +export type { SendTransactionResponse } from '@ton/walletkit'; +/** + * Transaction payload passed to {@link WalletInterface}'s `sendTransaction` — one or more messages, optional network override and `validUntil` deadline. + * + * @public + * @category Type + * @section Transactions + */ export interface TransactionRequest { - /** - * List of messages to include in the transaction - */ + /** Messages to include in the transaction. */ messages: TransactionRequestMessage[]; - /** - * Network to execute the transaction on - */ + /** Network to execute the transaction on. */ network?: Network; - /** - * Unix timestamp after which the transaction becomes invalid - */ + /** Unix timestamp (seconds) after which the transaction becomes invalid. */ validUntil?: number; - /** - * Sender wallet address in received format(raw, user friendly) - */ + /** Sender wallet address — accepts either raw or user-friendly format. */ fromAddress?: string; } /** - * Individual message within a transaction request. + * Individual message inside a {@link TransactionRequest} — recipient, amount, optional payload and contract `stateInit`. + * + * @public + * @category Type + * @section Transactions */ export interface TransactionRequestMessage { - /** - * Recipient wallet address in format received from caller (raw, user friendly) - */ + /** Recipient wallet address — accepts either raw or user-friendly format. */ address: string; - /** - * Amount to transfer in nanos - */ + /** Amount to transfer, in nano-TON (1 TON = 10⁹ nano-TON). */ amount: TokenAmount; - /** - * Additional currencies to include in the transfer - */ + /** Additional currencies to include in the transfer. */ extraCurrency?: ExtraCurrencies; - /** - * Initial state for deploying a new contract, encoded in Base64 - */ + /** Initial state for deploying a new contract, encoded as Base64. */ stateInit?: string; - /** - * Message payload data encoded in Base64 - */ + /** Message payload, encoded as Base64. */ payload?: string; } diff --git a/packages/appkit/src/types/utils.ts b/packages/appkit/src/types/utils.ts index 9206d8dee..a6b9c4400 100644 --- a/packages/appkit/src/types/utils.ts +++ b/packages/appkit/src/types/utils.ts @@ -32,7 +32,7 @@ export type FixedArray; -/** Checks if {@link type} can be narrowed further than {@link type2} */ +/** Checks if {@link type} can be narrowed further than {@link type2}. */ export type IsNarrowable = IsUnknown extends true ? false @@ -54,7 +54,7 @@ export type IsNever = [type] extends [never] ? true : false; */ export type IsUnknown = unknown extends type ? true : false; -/** Merges two object types into new type */ +/** Merges two object types into new type. */ export type Merge = Compute< LooseOmit & obj2 >; @@ -64,7 +64,7 @@ export type Mutable = { -readonly [key in keyof type]: type[key]; }; -/** Strict version of built-in Omit type */ +/** Strict version of built-in Omit type. */ export type StrictOmit = Pick>; /** Makes objects destructurable. */ @@ -105,7 +105,7 @@ export type ExactRequired = { /////////////////////////////////////////////////////////////////////////// // Loose types -/** Loose version of {@link StrictOmit} */ +/** Loose version of {@link StrictOmit}. */ export type LooseOmit = Pick>; /////////////////////////////////////////////////////////////////////////// diff --git a/packages/appkit/src/types/wallet.ts b/packages/appkit/src/types/wallet.ts index 81f42030f..c63c40f5d 100644 --- a/packages/appkit/src/types/wallet.ts +++ b/packages/appkit/src/types/wallet.ts @@ -6,44 +6,37 @@ * */ -import type { SendTransactionResponse, Hex, UserFriendlyAddress } from '@ton/walletkit'; - -import type { TransactionRequest } from './transaction'; +import type { Hex, UserFriendlyAddress } from './primitives'; +import type { TransactionRequest, SendTransactionResponse } from './transaction'; import type { SignDataRequest, SignDataResponse } from './signing'; import type { Network } from './network'; /** - * Minimal wallet interface for appkit. - * Only includes methods that require wallet-specific logic (signing, identity). - * Data fetching (balance, jettons, nfts) is done via actions using networkManager. + * Wallet contract surfaced by every {@link Connector} — covers identity (address, public key, network) and signing operations. Reads (balance, jettons, NFTs) go through AppKit actions instead. + * + * @public + * @category Type + * @section Wallets */ export interface WalletInterface { - /** Connector that created this wallet */ + /** ID of the {@link Connector} that produced this wallet. */ readonly connectorId: string; - // ========================================== - // Identity - // ========================================== - - /** Get the wallet address */ + /** Wallet address as a user-friendly base64url string. */ getAddress(): UserFriendlyAddress; - /** Get the wallet public key */ + /** Wallet public key as a `0x`-prefixed hex string. */ getPublicKey(): Hex; - /** Get the network the wallet is connected to */ + /** Network the wallet is currently connected to. */ getNetwork(): Network; - /** Get unique wallet identifier */ + /** Stable identifier combining address and network — unique across AppKit's connected wallets. */ getWalletId(): string; - // ========================================== - // Actions requiring wallet signature - // ========================================== - - /** Send a transaction (wallet signs and submits) */ + /** Send a transaction — the wallet signs and broadcasts it. */ sendTransaction(request: TransactionRequest): Promise; - /** Sign arbitrary data using TonConnect signData */ + /** Sign arbitrary data — text, binary or TON cell — through the wallet's sign-data flow. */ signData(payload: SignDataRequest): Promise; } diff --git a/packages/appkit/src/utils/amount/calc-fiat-value.ts b/packages/appkit/src/utils/amount/calc-fiat-value.ts index 8fc9de483..0fcbc2f65 100644 --- a/packages/appkit/src/utils/amount/calc-fiat-value.ts +++ b/packages/appkit/src/utils/amount/calc-fiat-value.ts @@ -7,8 +7,7 @@ */ /** - * Calculates the fiat value of a token amount. - * Returns null when rate is unavailable or amount is zero/invalid. + * Calculates the fiat value of a token amount. Returns `'0'` when the rate is unavailable or the amount is zero/invalid. */ export const calcFiatValue = (amount: string, rate: string | undefined): string => { if (!rate) return '0'; diff --git a/packages/appkit/src/utils/balance/calc-max-spendable.ts b/packages/appkit/src/utils/balance/calc-max-spendable.ts index 6b1a2533b..066cbe027 100644 --- a/packages/appkit/src/utils/balance/calc-max-spendable.ts +++ b/packages/appkit/src/utils/balance/calc-max-spendable.ts @@ -6,7 +6,7 @@ * */ -import { formatUnits, parseUnits } from '@ton/walletkit'; +import { formatUnits, parseUnits } from '..'; /** * Default TON reserve subtracted from balance when computing the max spendable amount @@ -27,9 +27,9 @@ export interface CalcMaxSpendableParams { } /** - * Compute the max spendable amount a user can place into an input when they click MAX. - * For native TON — subtracts a fixed reserve so the user still has room for network fees. - * For jettons — returns the full balance (gas is paid from TON separately). + * Compute the max amount a user can spend — used to populate the input when the user clicks MAX. + * For native TON: subtracts a fixed reserve so the user still has room for network fees. + * For jettons: returns the full balance (gas is paid from TON separately). */ export const calcMaxSpendable = ({ balance, diff --git a/packages/appkit/src/utils/balance/get-ton-shortfall.ts b/packages/appkit/src/utils/balance/get-ton-shortfall.ts index 732bd6336..5c2d66be9 100644 --- a/packages/appkit/src/utils/balance/get-ton-shortfall.ts +++ b/packages/appkit/src/utils/balance/get-ton-shortfall.ts @@ -6,7 +6,7 @@ * */ -import { formatUnits, parseUnits } from '@ton/walletkit'; +import { formatUnits, parseUnits } from '..'; /** Default extra TON buffer added on top of built transaction outflow when checking balance before sending. */ export const DEFAULT_GAS_BUFFER_NANOS = 100_000_000n; @@ -45,7 +45,7 @@ export interface GetTonShortfallParams { /** * Check whether the user's TON balance covers the built transaction. - * - Returns `null` if the balance is sufficient. + * - Returns `undefined` if the balance is sufficient. * - Returns `{ mode: 'reduce', ... }` with a smaller suggested `fromAmount` when `fromToken` is TON * and the balance is enough to cover at least gas (user can fix it by reducing the amount). * - Returns `{ mode: 'topup', ... }` when `fromToken` is a jetton (reducing jetton amount won't free up TON gas), diff --git a/packages/appkit/src/utils/functions/debounce.ts b/packages/appkit/src/utils/functions/debounce.ts index 29e3166b5..aa9f9e46a 100644 --- a/packages/appkit/src/utils/functions/debounce.ts +++ b/packages/appkit/src/utils/functions/debounce.ts @@ -49,9 +49,8 @@ export interface DebouncedFunction void> { } /** - * Creates a debounced function that delays invoking the provided function until after `debounceMs` milliseconds - * have elapsed since the last time the debounced function was invoked. The debounced function also has a `cancel` - * method to cancel any pending execution. + * Creates a debounced function that delays invoking `func` until `debounceMs` milliseconds have elapsed since the + * last call. The returned function exposes `cancel`, `schedule`, and `flush` for manual control. * * @template F - The type of function. * @param {F} func - The function to debounce. diff --git a/packages/appkit/src/utils/index.ts b/packages/appkit/src/utils/index.ts index 20ade7b66..bb81f623f 100644 --- a/packages/appkit/src/utils/index.ts +++ b/packages/appkit/src/utils/index.ts @@ -6,7 +6,26 @@ * */ -export { formatUnits, parseUnits, compareAddress } from '@ton/walletkit'; +export { + formatUnits, + parseUnits, + compareAddress, + asHex, + createWalletId, + getNormalizedExtMessageHash, + createCommentPayloadBase64, + createJettonTransferPayload, + createNftTransferPayload, + createTransferTransaction, + DEFAULT_JETTON_GAS_FEE, + DEFAULT_NFT_GAS_FEE, + getJettonBalanceFromClient, + getJettonWalletAddressFromClient, + getJettonsFromClient, + getNftFromClient, + getNftsFromClient, + getTransactionStatus as getTransactionStatusFromClient, +} from '@ton/walletkit'; export * from './address/format'; export * from './amount/calc-fiat-value'; diff --git a/packages/appkit/src/utils/jetton/jetton-info.ts b/packages/appkit/src/utils/jetton/jetton-info.ts index 02972ba34..3ce921407 100644 --- a/packages/appkit/src/utils/jetton/jetton-info.ts +++ b/packages/appkit/src/utils/jetton/jetton-info.ts @@ -6,7 +6,7 @@ * */ -import type { Jetton } from '@ton/walletkit'; +import type { Jetton } from '../../types/jetton'; export const getJettonsSymbol = (jetton: Jetton): string | undefined => { if (!jetton?.info?.symbol) { diff --git a/packages/appkit/src/utils/network/resolve-network.ts b/packages/appkit/src/utils/network/resolve-network.ts index 91ddf1111..76e68ded1 100644 --- a/packages/appkit/src/utils/network/resolve-network.ts +++ b/packages/appkit/src/utils/network/resolve-network.ts @@ -18,7 +18,7 @@ import { getDefaultNetwork } from '../../actions/network/get-default-network'; * 1. Explicitly passed `network` parameter * 2. Selected wallet's network * 3. Configured default network - * 4. Mainnet (last resort) + * 4. Mainnet, when nothing else is configured. */ export const resolveNetwork = (appKit: AppKit, network?: Network): Network => { if (network) return network; diff --git a/packages/appkit/src/utils/nft/nft-info.ts b/packages/appkit/src/utils/nft/nft-info.ts index 7added6e9..5ef95d89c 100644 --- a/packages/appkit/src/utils/nft/nft-info.ts +++ b/packages/appkit/src/utils/nft/nft-info.ts @@ -6,8 +6,7 @@ * */ -import type { NFT } from '@ton/walletkit'; - +import type { NFT } from '../../types/nft'; import { middleEllipsis } from '../string/middle-ellipsis'; export const getNftImage = (nft: NFT): string | null => { diff --git a/packages/mcp/src/tools/wallet-management-tools.ts b/packages/mcp/src/tools/wallet-management-tools.ts index 82b291548..97ffefb79 100644 --- a/packages/mcp/src/tools/wallet-management-tools.ts +++ b/packages/mcp/src/tools/wallet-management-tools.ts @@ -60,11 +60,11 @@ const setNetworkConfigSchema = z.object({ }); const setActiveWalletSchema = z.object({ - walletSelector: z.string().min(1).describe('Wallet id, name, or address'), + walletSelector: z.string().min(1).describe('Wallet ID, name, or address'), }); const removeWalletSchema = z.object({ - walletSelector: z.string().min(1).describe('Wallet id, name, or address to remove'), + walletSelector: z.string().min(1).describe('Wallet ID, name, or address to remove'), }); const validateAgenticWalletSchema = z.object({ diff --git a/packages/walletkit/README.md b/packages/walletkit/README.md index 6b461544d..492b7bcdc 100644 --- a/packages/walletkit/README.md +++ b/packages/walletkit/README.md @@ -1,7 +1,7 @@ # TonWalletKit @@ -213,7 +213,7 @@ if (!wallet) { } // Query balance const balance = await wallet.getBalance(); -console.log('WalletBalance', wallet.getAddress(), balance.toString()); +console.log('WalletBalance', wallet.getAddress(), balance); ``` ### Rendering previews (reference) diff --git a/packages/walletkit/src/api/interfaces/CryptoOnrampAPI.ts b/packages/walletkit/src/api/interfaces/CryptoOnrampAPI.ts index 80b3f086c..acd81d490 100644 --- a/packages/walletkit/src/api/interfaces/CryptoOnrampAPI.ts +++ b/packages/walletkit/src/api/interfaces/CryptoOnrampAPI.ts @@ -53,6 +53,7 @@ export interface CryptoOnrampProviderInterface< TQuoteOptions = unknown, TDepositOptions = unknown, > extends DefiProvider { + /** Provider kind discriminator pinned to `'crypto-onramp'` so {@link registerProvider} routes it to the crypto-onramp manager. */ readonly type: 'crypto-onramp'; /** diff --git a/packages/walletkit/src/api/interfaces/DefiManagerAPI.ts b/packages/walletkit/src/api/interfaces/DefiManagerAPI.ts index c4ceabe8d..a3480633e 100644 --- a/packages/walletkit/src/api/interfaces/DefiManagerAPI.ts +++ b/packages/walletkit/src/api/interfaces/DefiManagerAPI.ts @@ -14,6 +14,7 @@ import type { DefiProvider } from './DefiProvider'; * Swap API interface exposed by SwapManager */ export interface DefiManagerAPI { + /** Build a fresh {@link ProviderFactoryContext} the manager hands to provider factories at registration time. */ createFactoryContext(): ProviderFactoryContext; /** * Register a new provider. If a provider with the same id is already registered, it is replaced. diff --git a/packages/walletkit/src/api/interfaces/DefiProvider.ts b/packages/walletkit/src/api/interfaces/DefiProvider.ts index 2d8c9a24a..c59b10691 100644 --- a/packages/walletkit/src/api/interfaces/DefiProvider.ts +++ b/packages/walletkit/src/api/interfaces/DefiProvider.ts @@ -17,6 +17,7 @@ export type DefiProviderType = 'swap' | 'staking' | 'onramp' | 'crypto-onramp'; * Base interface for all DeFi providers */ export interface DefiProvider extends BaseProvider { + /** Provider kind discriminator narrowed to the DeFi-domain literals so the right manager picks it up at registration time. */ readonly type: DefiProviderType; /** diff --git a/packages/walletkit/src/api/interfaces/index.ts b/packages/walletkit/src/api/interfaces/index.ts index dda0eb1c7..c96be575a 100644 --- a/packages/walletkit/src/api/interfaces/index.ts +++ b/packages/walletkit/src/api/interfaces/index.ts @@ -15,7 +15,7 @@ export type { DefiManagerAPI } from './DefiManagerAPI'; export type { SwapAPI, SwapProviderInterface } from './SwapAPI'; export type { OnrampAPI, OnrampProviderInterface } from './OnrampAPI'; export type { CryptoOnrampAPI, CryptoOnrampProviderInterface } from './CryptoOnrampAPI'; -export type { DefiProvider } from './DefiProvider'; +export type { DefiProvider, DefiProviderType } from './DefiProvider'; export type { StakingAPI, StakingProviderInterface } from './StakingAPI'; export type { TONConnectSessionManager } from './TONConnectSessionManager'; diff --git a/packages/walletkit/src/api/models/blockchain/MasterchainInfo.ts b/packages/walletkit/src/api/models/blockchain/MasterchainInfo.ts index 4ccd750d0..286df43c8 100644 --- a/packages/walletkit/src/api/models/blockchain/MasterchainInfo.ts +++ b/packages/walletkit/src/api/models/blockchain/MasterchainInfo.ts @@ -19,7 +19,7 @@ export interface MasterchainInfo { seqno: number; /** - * Shard identifier of the block + * Shard identifier of the block. */ shard: string; @@ -30,12 +30,12 @@ export interface MasterchainInfo { workchain: number; /** - * File hash of the block + * File hash of the block. */ fileHash: Hex; /** - * Root hash of the block + * Root hash of the block. */ rootHash: Hex; } diff --git a/packages/walletkit/src/api/models/bridge/BridgeEvent.ts b/packages/walletkit/src/api/models/bridge/BridgeEvent.ts index 9d38640aa..e05f17c45 100644 --- a/packages/walletkit/src/api/models/bridge/BridgeEvent.ts +++ b/packages/walletkit/src/api/models/bridge/BridgeEvent.ts @@ -14,21 +14,21 @@ import type { UserFriendlyAddress } from '../core/Primitives'; */ export interface BridgeEvent { /** - * Unique identifier for the bridge event + * Unique identifier for the bridge event. */ id: string; from?: string; /** - * Wallet address associated with the event + * Wallet address associated with the event. */ walletAddress?: UserFriendlyAddress; /** - * Wallet identifier associated with the event + * Wallet identifier associated with the event. */ walletId?: string; /** - * Domain of the dApp that initiated the event + * Domain of the dApp that initiated the event. */ domain?: string; /** @@ -36,11 +36,11 @@ export interface BridgeEvent { */ isJsBridge?: boolean; /** - * Browser tab ID for JS Bridge events + * Browser tab ID for JS Bridge events. */ tabId?: string; /** - * Session identifier for the connection + * Session identifier for the connection. */ sessionId?: string; isLocal?: boolean; diff --git a/packages/walletkit/src/api/models/bridge/ConnectionRequestEvent.ts b/packages/walletkit/src/api/models/bridge/ConnectionRequestEvent.ts index c067db7e1..21e78d00e 100644 --- a/packages/walletkit/src/api/models/bridge/ConnectionRequestEvent.ts +++ b/packages/walletkit/src/api/models/bridge/ConnectionRequestEvent.ts @@ -18,7 +18,7 @@ export interface ConnectionRequestEvent extends BridgeEvent { */ requestedItems: ConnectionRequestEventRequestedItem[]; /** - * Preview information for UI display + * Preview information for UI display. */ preview: ConnectionRequestEventPreview; } @@ -28,11 +28,11 @@ export interface ConnectionRequestEvent extends BridgeEvent { */ export interface ConnectionRequestEventPreview { /** - * Permissions requested by the dApp + * Permissions requested by the dApp. */ permissions: ConnectionRequestEventPreviewPermission[]; /** - * Information about the requesting dApp + * Information about the requesting dApp. */ dAppInfo?: DAppInfo; /** @@ -62,15 +62,15 @@ export interface ConnectionRequestTonProofRequestedItem { */ export interface ConnectionRequestEventPreviewPermission { /** - * Identifier name of the permission + * Identifier name of the permission. */ name?: string; /** - * Human-readable title of the permission + * Human-readable title of the permission. */ title?: string; /** - * Detailed description of what the permission allows + * Detailed description of what the permission allows. */ description?: string; } diff --git a/packages/walletkit/src/api/models/bridge/DisconnectionEvent.ts b/packages/walletkit/src/api/models/bridge/DisconnectionEvent.ts index bb671c74d..5a39afe90 100644 --- a/packages/walletkit/src/api/models/bridge/DisconnectionEvent.ts +++ b/packages/walletkit/src/api/models/bridge/DisconnectionEvent.ts @@ -14,7 +14,7 @@ import type { DAppInfo } from '../core/DAppInfo'; */ export interface DisconnectionEvent extends BridgeEvent { /** - * Preview information for UI display + * Preview information for UI display. */ preview: DisconnectionEventPreview; } @@ -24,11 +24,11 @@ export interface DisconnectionEvent extends BridgeEvent { */ export interface DisconnectionEventPreview { /** - * Human-readable reason for the disconnection + * Human-readable reason for the disconnection. */ reason?: string; /** - * Information about the disconnected dApp + * Information about the disconnected dApp. */ dAppInfo?: DAppInfo; } diff --git a/packages/walletkit/src/api/models/bridge/RequestErrorEvent.ts b/packages/walletkit/src/api/models/bridge/RequestErrorEvent.ts index a3441164e..52c1a0a7f 100644 --- a/packages/walletkit/src/api/models/bridge/RequestErrorEvent.ts +++ b/packages/walletkit/src/api/models/bridge/RequestErrorEvent.ts @@ -10,16 +10,16 @@ import type { ResultError } from '../core/Primitives'; export interface RequestErrorEvent { /** - * Unique identifier for the request that resulted in an error + * Unique identifier for the request that resulted in an error. */ id: string; /** - * Error details for the request failure + * Error details for the request failure. */ error: ResultError; /** - * Additional data related to the error event + * Additional data related to the error event. */ data: { [k: string]: unknown }; } diff --git a/packages/walletkit/src/api/models/bridge/SendTransactionApprovalResponse.ts b/packages/walletkit/src/api/models/bridge/SendTransactionApprovalResponse.ts index 22bb4ca1a..e199da7b3 100644 --- a/packages/walletkit/src/api/models/bridge/SendTransactionApprovalResponse.ts +++ b/packages/walletkit/src/api/models/bridge/SendTransactionApprovalResponse.ts @@ -13,7 +13,7 @@ import type { Base64String } from '../core/Primitives'; */ export interface SendTransactionApprovalResponse { /** - * Signed transaction in BOC (Bag of Cells) format, encoded in Base64 + * Signed transaction in BoC (Bag of Cells) format, encoded in Base64. */ signedBoc: Base64String; } diff --git a/packages/walletkit/src/api/models/bridge/SendTransactionRequestEvent.ts b/packages/walletkit/src/api/models/bridge/SendTransactionRequestEvent.ts index ac8b58cc6..2da6aed41 100644 --- a/packages/walletkit/src/api/models/bridge/SendTransactionRequestEvent.ts +++ b/packages/walletkit/src/api/models/bridge/SendTransactionRequestEvent.ts @@ -15,11 +15,11 @@ import type { BridgeEvent } from './BridgeEvent'; */ export interface SendTransactionRequestEvent extends BridgeEvent { /** - * Preview information for UI display + * Preview information for UI display. */ preview: SendTransactionRequestEventPreview; /** - * Raw transaction request data + * Raw transaction request data. */ request: TransactionRequest; } @@ -29,7 +29,7 @@ export interface SendTransactionRequestEvent extends BridgeEvent { */ export interface SendTransactionRequestEventPreview { /** - * Emulated transaction preview with actions and traces + * Emulated transaction preview with actions and traces. */ data?: TransactionEmulatedPreview; } diff --git a/packages/walletkit/src/api/models/bridge/SignDataApprovalResponse.ts b/packages/walletkit/src/api/models/bridge/SignDataApprovalResponse.ts index b09ec627e..94b92f25a 100644 --- a/packages/walletkit/src/api/models/bridge/SignDataApprovalResponse.ts +++ b/packages/walletkit/src/api/models/bridge/SignDataApprovalResponse.ts @@ -13,7 +13,7 @@ import type { Hex } from '../core/Primitives'; */ export interface SignDataApprovalResponse { /** - * Cryptographic signature of the signed data in hexadecimal format + * Cryptographic signature of the signed data in hexadecimal format. */ signature: Hex; /** @@ -22,7 +22,7 @@ export interface SignDataApprovalResponse { */ timestamp: number; /** - * Domain associated with the sign request + * Domain associated with the sign request. */ domain: string; } diff --git a/packages/walletkit/src/api/models/bridge/SignDataRequestEvent.ts b/packages/walletkit/src/api/models/bridge/SignDataRequestEvent.ts index df1d3f23d..bacf41f65 100644 --- a/packages/walletkit/src/api/models/bridge/SignDataRequestEvent.ts +++ b/packages/walletkit/src/api/models/bridge/SignDataRequestEvent.ts @@ -16,11 +16,11 @@ import type { SignDataBinary, SignDataCell, SignDataText } from '../core/SignDat */ export interface SignDataRequestEvent extends BridgeEvent { /** - * Payload containing the data to be signed + * Payload containing the data to be signed. */ payload: SignDataPayload; /** - * Preview information for UI display + * Preview information for UI display. */ preview: SignDataRequestEventPreview; } @@ -30,12 +30,12 @@ export interface SignDataRequestEvent extends BridgeEvent { */ export interface SignDataRequestEventPreview { /** - * Information about the requesting dApp + * Information about the requesting dApp. */ dAppInfo?: DAppInfo; /** - * Array of sign data previews + * Array of sign data previews. */ data: SignDataPreview; } diff --git a/packages/walletkit/src/api/models/core/AddressBook.ts b/packages/walletkit/src/api/models/core/AddressBook.ts index 9a2f31fe9..ad1388ac8 100644 --- a/packages/walletkit/src/api/models/core/AddressBook.ts +++ b/packages/walletkit/src/api/models/core/AddressBook.ts @@ -15,17 +15,17 @@ export type AddressBook = { [key: UserFriendlyAddress]: AddressBookEntry }; export interface AddressBookEntry { /** - * The human-readable representation of the blockchain address + * The human-readable representation of the blockchain address. */ address?: UserFriendlyAddress; /** - * The domain name associated with the address if available + * The domain name associated with the address if available. */ domain?: string; /** - * List of supported interfaces by the address + * List of supported interfaces by the address. */ interfaces: string[]; } diff --git a/packages/walletkit/src/api/models/core/AssetType.ts b/packages/walletkit/src/api/models/core/AssetType.ts index 3655345fe..be3b1fda5 100644 --- a/packages/walletkit/src/api/models/core/AssetType.ts +++ b/packages/walletkit/src/api/models/core/AssetType.ts @@ -11,7 +11,7 @@ */ export enum AssetType { /** - * Native TON cryptocurrency + * Native TON cryptocurrency. */ ton = 'ton', /** diff --git a/packages/walletkit/src/api/models/core/BaseProvider.ts b/packages/walletkit/src/api/models/core/BaseProvider.ts index 4caed3acf..8fde15e47 100644 --- a/packages/walletkit/src/api/models/core/BaseProvider.ts +++ b/packages/walletkit/src/api/models/core/BaseProvider.ts @@ -10,16 +10,22 @@ * Base interface shared by all provider types. */ export interface BaseProvider { + /** Stable provider identifier, unique within the manager that registered it. */ readonly providerId: string; + /** Provider kind discriminator (e.g., `'swap'`, `'staking'`, `'onramp'`, `'crypto-onramp'`). Used to route registrations to the right manager. */ readonly type: string; } export interface BaseProviderUpdate { + /** Stable id of the affected provider — same as the `providerId` it was registered with. */ providerId: string; + /** Provider-kind discriminator (e.g., `'swap'`, `'staking'`, `'onramp'`, `'crypto-onramp'`) — same as the provider's `type`. */ type: string; } export interface BaseProviderEvents { + /** Fired by a DeFi manager when a provider is registered through it (carries the provider's id and kind). */ 'provider:registered': BaseProviderUpdate; + /** Fired by a DeFi manager when its default provider is set or cleared (carries the new default's id and kind). */ 'provider:default-changed': BaseProviderUpdate; } diff --git a/packages/walletkit/src/api/models/core/DAppInfo.ts b/packages/walletkit/src/api/models/core/DAppInfo.ts index 4362c37b7..721c6a9ad 100644 --- a/packages/walletkit/src/api/models/core/DAppInfo.ts +++ b/packages/walletkit/src/api/models/core/DAppInfo.ts @@ -11,12 +11,12 @@ */ export interface DAppInfo { /** - * Display name of the dApp + * Display name of the dApp. */ name?: string; /** - * Brief description of the dApp's purpose + * Brief description of the dApp's purpose. */ description?: string; diff --git a/packages/walletkit/src/api/models/core/Network.ts b/packages/walletkit/src/api/models/core/Network.ts index bfcec4086..c8544158f 100644 --- a/packages/walletkit/src/api/models/core/Network.ts +++ b/packages/walletkit/src/api/models/core/Network.ts @@ -34,7 +34,7 @@ export const Network = { tetra: (): Network => ({ chainId: '662387' }), /** - * Custom network with specified chain ID + * Custom network with specified chain ID. */ custom: (chainId: string): Network => ({ chainId }), }; diff --git a/packages/walletkit/src/api/models/core/PreparedSignData.ts b/packages/walletkit/src/api/models/core/PreparedSignData.ts index 3d07a9730..871a59dfa 100644 --- a/packages/walletkit/src/api/models/core/PreparedSignData.ts +++ b/packages/walletkit/src/api/models/core/PreparedSignData.ts @@ -15,11 +15,11 @@ import type { SignData } from './SignData'; */ export interface PreparedSignData { /** - * Wallet address that will sign the data + * Wallet address that will sign the data. */ address: UserFriendlyAddress; /** - * Unix timestamp when the sign request was created + * Unix timestamp when the sign request was created. */ timestamp: number; /** @@ -27,11 +27,11 @@ export interface PreparedSignData { */ domain: string; /** - * Payload containing the data to be signed + * Payload containing the data to be signed. */ payload: SignDataPayload; /** - * Hash of the prepared sign data for verification + * Hash of the prepared sign data for verification. */ hash: Hex; } @@ -41,7 +41,7 @@ export interface PreparedSignData { */ export interface SignDataPayload { /** - * Network where the signing will occur + * Network where the signing will occur. */ network?: Network; /** @@ -49,22 +49,22 @@ export interface SignDataPayload { */ fromAddress?: string; /** - * Sign data content to be signed + * Sign data content to be signed. */ data: SignData; } export interface UnpreparedSignData { /** - * Payload containing the data to be signed + * Payload containing the data to be signed. */ payload: SignDataPayload; /** - * Requesting domain for the signature + * Requesting domain for the signature. */ domain: string; /** - * Wallet address that will sign the data + * Wallet address that will sign the data. */ address: UserFriendlyAddress; } diff --git a/packages/walletkit/src/api/models/core/Primitives.ts b/packages/walletkit/src/api/models/core/Primitives.ts index ffd83d1b6..a2ddd4d49 100644 --- a/packages/walletkit/src/api/models/core/Primitives.ts +++ b/packages/walletkit/src/api/models/core/Primitives.ts @@ -21,7 +21,7 @@ declare const hashBrand: unique symbol; export type Hex = `0x${string}` & { readonly [hashBrand]: never }; /** - * Base64-encoded string representation + * Base64-encoded string representation. */ declare const base64StringBrand: unique symbol; @@ -29,7 +29,7 @@ declare const base64StringBrand: unique symbol; export type Base64String = string & { readonly [base64StringBrand]: never }; /** - * Logical time value used for ordering transactions on the TON blockchain + * Logical time value used for ordering transactions on the TON blockchain. */ export type LogicalTime = string; @@ -38,11 +38,11 @@ export type LogicalTime = string; */ export enum Result { /** - * Operation completed successfully + * Operation completed successfully. */ success = 'success', /** - * Operation failed + * Operation failed. */ failure = 'failure', } @@ -58,12 +58,12 @@ export interface ResultError { code?: number; /** - * Human-readable error message + * Human-readable error message. */ message?: string; /** - * Additional error data + * Additional error data. */ data?: unknown; } diff --git a/packages/walletkit/src/api/models/core/ProofMessage.ts b/packages/walletkit/src/api/models/core/ProofMessage.ts index 1200be902..87c3523a8 100644 --- a/packages/walletkit/src/api/models/core/ProofMessage.ts +++ b/packages/walletkit/src/api/models/core/ProofMessage.ts @@ -18,7 +18,7 @@ export interface ProofMessage { */ workchain: number; /** - * Wallet address hash in hexadecimal format + * Wallet address hash in hexadecimal format. */ addressHash: Hex; /** @@ -27,19 +27,19 @@ export interface ProofMessage { */ timestamp: number; /** - * Domain information for the proof request + * Domain information for the proof request. */ domain: ProofMessageDomain; /** - * Payload string to be signed + * Payload string to be signed. */ payload: string; /** - * Initial state of the wallet contract encoded in Base64 + * Initial state of the wallet contract encoded in Base64. */ stateInit: Base64String; /** - * Cryptographic signature of the proof message + * Cryptographic signature of the proof message. */ signature?: Hex; } diff --git a/packages/walletkit/src/api/models/core/SendMode.ts b/packages/walletkit/src/api/models/core/SendMode.ts index ea29d8940..fbb104e23 100644 --- a/packages/walletkit/src/api/models/core/SendMode.ts +++ b/packages/walletkit/src/api/models/core/SendMode.ts @@ -19,15 +19,15 @@ export interface SendMode { */ export enum SendModeBase { /** - * Ordinary message + * Ordinary message. */ ORDINARY = 0, /** - * Carry all the remaining value of the inbound message in addition to the value initially indicated in the new message + * Carry all the remaining value of the inbound message in addition to the value initially indicated in the new message. */ CARRY_ALL_REMAINING_INCOMING_VALUE = 64, /** - * Carry all the remaining balance of the current smart contract instead of the value originally indicated in the message + * Carry all the remaining balance of the current smart contract instead of the value originally indicated in the message. */ CARRY_ALL_REMAINING_BALANCE = 128, } @@ -45,11 +45,11 @@ export enum SendModeFlag { */ BOUNCE_IF_FAILURE = 16, /** - * Ignore some errors arising while processing this message during the action phase + * Ignore some errors arising while processing this message during the action phase. */ IGNORE_ERRORS = 2, /** - * Pay transfer fees separately from the message value + * Pay transfer fees separately from the message value. */ PAY_GAS_SEPARATELY = 1, } diff --git a/packages/walletkit/src/api/models/core/SignData.ts b/packages/walletkit/src/api/models/core/SignData.ts index adfda8634..547d36d37 100644 --- a/packages/walletkit/src/api/models/core/SignData.ts +++ b/packages/walletkit/src/api/models/core/SignData.ts @@ -21,7 +21,7 @@ export type SignData = */ export interface SignDataBinary { /** - * Raw binary content encoded as bytes in Base64 + * Raw binary content encoded as bytes in Base64. */ content: Base64String; } @@ -31,11 +31,11 @@ export interface SignDataBinary { */ export interface SignDataCell { /** - * Schema describing the cell structure for parsing + * Schema describing the cell structure for parsing. */ schema: string; /** - * Cell content encoded in Base64 + * Cell content encoded in Base64. */ content: Base64String; } @@ -45,7 +45,7 @@ export interface SignDataCell { */ export interface SignDataText { /** - * Text content to be signed + * Text content to be signed. */ content: string; } diff --git a/packages/walletkit/src/api/models/core/TokenAnimation.ts b/packages/walletkit/src/api/models/core/TokenAnimation.ts index c54dc13b4..8a59fcbd8 100644 --- a/packages/walletkit/src/api/models/core/TokenAnimation.ts +++ b/packages/walletkit/src/api/models/core/TokenAnimation.ts @@ -17,7 +17,7 @@ export interface TokenAnimation { url?: string; /** - * Optional Lottie animation data as a string + * Optional Lottie animation data as a string. */ lottie?: string; } diff --git a/packages/walletkit/src/api/models/core/TokenInfo.ts b/packages/walletkit/src/api/models/core/TokenInfo.ts index a69a93921..511d4251b 100644 --- a/packages/walletkit/src/api/models/core/TokenInfo.ts +++ b/packages/walletkit/src/api/models/core/TokenInfo.ts @@ -14,22 +14,22 @@ import type { TokenAnimation } from './TokenAnimation'; */ export interface TokenInfo { /** - * Display name of the token + * Display name of the token. */ name?: string; /** - * Human-readable description of the token + * Human-readable description of the token. */ description?: string; /** - * Token image in various sizes + * Token image in various sizes. */ image?: TokenImage; /** - * Animated media associated with the token + * Animated media associated with the token. */ animation?: TokenAnimation; diff --git a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampDeposit.ts b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampDeposit.ts index a3c4008fc..8ccf42d46 100644 --- a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampDeposit.ts +++ b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampDeposit.ts @@ -10,22 +10,21 @@ * Deposit details returned by a crypto onramp provider. * * The user must send `amount` of `sourceCurrencyAddress` to `address` on `sourceChain` - * to complete the onramp; the provider then delivers the target crypto to the - * user's TON address. + * to complete the onramp. The provider then delivers the target crypto to the user's TON address. */ export interface CryptoOnrampDeposit { /** - * Deposit id + * Deposit id. */ depositId: string; /** - * Deposit address on the source chain + * Deposit address on the source chain. */ address: string; /** - * Exact amount of source crypto the user must send + * Exact amount of source crypto the user must send. */ amount: string; @@ -47,7 +46,7 @@ export interface CryptoOnrampDeposit { memo?: string; /** - * Unix timestamp (ms) after which the deposit offer is no longer valid + * Unix timestamp (ms) after which the deposit offer is no longer valid. */ expiresAt?: number; @@ -57,7 +56,7 @@ export interface CryptoOnrampDeposit { chainWarning?: string; /** - * Identifier of the provider that issued this deposit + * Identifier of the provider that issued this deposit. */ providerId: string; } diff --git a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampDepositParams.ts b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampDepositParams.ts index 3ec0aa586..cdb83a61f 100644 --- a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampDepositParams.ts +++ b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampDepositParams.ts @@ -20,12 +20,12 @@ export interface CryptoOnrampDepositParams; /** - * Address to refund the crypto to in case of failure + * Address to refund the crypto to in case of failure. */ refundAddress: string; /** - * Provider-specific options + * Provider-specific options. */ providerOptions?: TProviderOptions; } diff --git a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampProviderMetadata.ts b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampProviderMetadata.ts index 3df0c4fca..afd4979fb 100644 --- a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampProviderMetadata.ts +++ b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampProviderMetadata.ts @@ -16,12 +16,12 @@ export interface CryptoOnrampProviderMetadata { name: string; /** - * URL to the provider's logo image + * URL to the provider's logo image. */ logo?: string; /** - * URL to the provider's website + * URL to the provider's website. */ url?: string; @@ -43,17 +43,17 @@ export interface CryptoOnrampProviderMetadata { */ export interface CryptoOnrampProviderMetadataOverride { /** - * Override the provider's display name + * Override the provider's display name. */ name?: string; /** - * Override the provider's logo URL + * Override the provider's logo URL. */ logo?: string; /** - * Override the provider's website URL + * Override the provider's website URL. */ url?: string; } diff --git a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampQuote.ts b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampQuote.ts index a9e466a03..477af0f30 100644 --- a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampQuote.ts +++ b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampQuote.ts @@ -7,7 +7,7 @@ */ /** - * Crypto onramp quote response with pricing information + * Crypto onramp quote response with pricing information. */ export interface CryptoOnrampQuote { /** @@ -28,12 +28,12 @@ export interface CryptoOnrampQuote { targetCurrencyAddress: string; /** - * Amount of source crypto to send + * Amount of source crypto to send. */ sourceAmount: string; /** - * Amount of target crypto to receive + * Amount of target crypto to receive. */ targetAmount: string; @@ -43,12 +43,12 @@ export interface CryptoOnrampQuote { rate: string; /** - * TON address that will receive the target crypto + * TON address that will receive the target crypto. */ recipientAddress: string; /** - * Identifier of the crypto onramp provider + * Identifier of the crypto onramp provider. */ providerId: string; diff --git a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampQuoteParams.ts b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampQuoteParams.ts index b31d22204..c9ee189ee 100644 --- a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampQuoteParams.ts +++ b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampQuoteParams.ts @@ -37,12 +37,12 @@ export interface CryptoOnrampQuoteParams { targetCurrencyAddress: string; /** - * TON address that will receive the target crypto + * TON address that will receive the target crypto. */ recipientAddress: string; /** - * Refund address for the source crypto + * Refund address for the source crypto. */ refundAddress?: string; @@ -54,7 +54,7 @@ export interface CryptoOnrampQuoteParams { isSourceAmount?: boolean; /** - * Provider-specific options + * Provider-specific options. */ providerOptions?: TProviderOptions; } diff --git a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampStatus.ts b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampStatus.ts index 29d3dfe89..3048b4edb 100644 --- a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampStatus.ts +++ b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampStatus.ts @@ -7,10 +7,6 @@ */ /** - * Deposit details returned by a crypto onramp provider. - * - * The user must send `amount` of `sourceCurrencyAddress` to `address` on `sourceChain` - * to complete the onramp; the provider then delivers the target crypto to the - * user's TON address. + * Final state of a crypto-onramp deposit — `'success'` (delivered to the recipient), `'pending'` (still in flight) or `'failed'` (provider could not complete the deposit). */ export type CryptoOnrampStatus = 'success' | 'pending' | 'failed'; diff --git a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampStatusParams.ts b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampStatusParams.ts index 91eb30647..b83e54b01 100644 --- a/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampStatusParams.ts +++ b/packages/walletkit/src/api/models/crypto-onramp/CryptoOnrampStatusParams.ts @@ -7,20 +7,16 @@ */ /** - * Deposit details returned by a crypto onramp provider. - * - * The user must send `amount` of `sourceCurrencyAddress` to `address` on `sourceChain` - * to complete the onramp; the provider then delivers the target crypto to the - * user's TON address. + * Parameters identifying a previously created crypto-onramp deposit — pair of `depositId` and the `providerId` that issued it. */ export interface CryptoOnrampStatusParams { /** - * Deposit id + * Deposit id. */ depositId: string; /** - * Identifier of the provider that issued this deposit + * Identifier of the provider that issued this deposit. */ providerId: string; } diff --git a/packages/walletkit/src/api/models/index.ts b/packages/walletkit/src/api/models/index.ts index d24b66eee..1fb1be83e 100644 --- a/packages/walletkit/src/api/models/index.ts +++ b/packages/walletkit/src/api/models/index.ts @@ -102,7 +102,7 @@ export type { OnrampQuoteParams } from './onramp/OnrampQuoteParams'; export type { OnrampLimits } from './onramp/OnrampLimits'; export type { OnrampLimitParams } from './onramp/OnrampLimitParams'; -// Crypto onramp models +// Crypto Onramp models export type { CryptoOnrampQuote } from './crypto-onramp/CryptoOnrampQuote'; export type { CryptoOnrampQuoteParams } from './crypto-onramp/CryptoOnrampQuoteParams'; export type { CryptoOnrampDepositParams } from './crypto-onramp/CryptoOnrampDepositParams'; diff --git a/packages/walletkit/src/api/models/jettons/Jetton.ts b/packages/walletkit/src/api/models/jettons/Jetton.ts index 9493408f4..a5f598305 100644 --- a/packages/walletkit/src/api/models/jettons/Jetton.ts +++ b/packages/walletkit/src/api/models/jettons/Jetton.ts @@ -15,22 +15,22 @@ import type { TokenInfo } from '../core/TokenInfo'; */ export interface Jetton { /** - * The Jetton contract address + * The jetton master contract address (the token itself). */ address: UserFriendlyAddress; /** - * The Jetton wallet address + * The owner's jetton-wallet contract address — the per-owner contract that actually holds this balance. */ walletAddress: UserFriendlyAddress; /** - * The current jetton balance + * The current jetton balance. */ balance: TokenAmount; /** - * Information about the token + * Information about the token. */ info: TokenInfo; @@ -41,17 +41,17 @@ export interface Jetton { decimalsNumber?: number; /** - * Indicates if the jetton is verified + * Indicates if the jetton is verified. */ isVerified: boolean; /** - * Current prices of the jetton in various currencies + * Current prices of the jetton in various currencies. */ prices: JettonPrice[]; /** - * Additional arbitrary data related to the jetton + * Additional arbitrary data related to the jetton. */ extra?: { [key: string]: unknown }; } diff --git a/packages/walletkit/src/api/models/jettons/JettonsRequest.ts b/packages/walletkit/src/api/models/jettons/JettonsRequest.ts index ff45d06ea..c55819be6 100644 --- a/packages/walletkit/src/api/models/jettons/JettonsRequest.ts +++ b/packages/walletkit/src/api/models/jettons/JettonsRequest.ts @@ -13,7 +13,7 @@ import type { Pagination } from '../core/Primitives'; */ export interface JettonsRequest { /** - * Pagination information + * Pagination information. */ pagination: Pagination; } diff --git a/packages/walletkit/src/api/models/jettons/JettonsResponse.ts b/packages/walletkit/src/api/models/jettons/JettonsResponse.ts index 9594c4ac8..682b02db8 100644 --- a/packages/walletkit/src/api/models/jettons/JettonsResponse.ts +++ b/packages/walletkit/src/api/models/jettons/JettonsResponse.ts @@ -14,11 +14,11 @@ import type { Jetton } from './Jetton'; */ export interface JettonsResponse { /** - * Address book mapping + * Address book mapping. */ addressBook: AddressBook; /** - * List of Jettons + * List of Jettons. */ jettons: Jetton[]; } diff --git a/packages/walletkit/src/api/models/jettons/JettonsTransferRequest.ts b/packages/walletkit/src/api/models/jettons/JettonsTransferRequest.ts index e0945c8f5..f19d72b61 100644 --- a/packages/walletkit/src/api/models/jettons/JettonsTransferRequest.ts +++ b/packages/walletkit/src/api/models/jettons/JettonsTransferRequest.ts @@ -14,22 +14,22 @@ import type { TokenAmount } from '../core/TokenAmount'; */ export interface JettonsTransferRequest { /** - * Jetton master contract address + * Jetton master contract address. */ jettonAddress: UserFriendlyAddress; /** - * Amount to transfer in Jetton's smallest unit + * Amount to transfer in Jetton's smallest unit. */ transferAmount: TokenAmount; /** - * Recipient wallet address + * Recipient wallet address. */ recipientAddress: UserFriendlyAddress; /** - * Human-readable comment attached to the transfer + * Human-readable comment attached to the transfer. */ comment?: string; } diff --git a/packages/walletkit/src/api/models/nfts/NFT.ts b/packages/walletkit/src/api/models/nfts/NFT.ts index 20dd6cc71..20c7a8d5e 100644 --- a/packages/walletkit/src/api/models/nfts/NFT.ts +++ b/packages/walletkit/src/api/models/nfts/NFT.ts @@ -16,12 +16,12 @@ import type { NFTCollection } from './NFTCollection'; */ export interface NFT { /** - * Contract address of the NFT item + * Contract address of the NFT item. */ address: UserFriendlyAddress; /** - * Index of the item within its collection + * Index of the item within its collection. */ index?: string; @@ -36,27 +36,27 @@ export interface NFT { attributes?: NFTAttribute[]; /** - * Information about the collection this item belongs to + * Information about the collection this item belongs to. */ collection?: NFTCollection; /** - * Address of the auction contract, if the NFT is being auctioned + * Address of the auction contract, if the NFT is being auctioned. */ auctionContractAddress?: UserFriendlyAddress; /** - * Hash of the NFT smart contract code + * Hash of the NFT smart contract code. */ codeHash?: Hex; /** - * Hash of the NFT's on-chain data + * Hash of the NFT's on-chain data. */ dataHash?: Hex; /** - * Whether the NFT contract has been initialized + * Whether the NFT contract has been initialized. */ isInited?: boolean; @@ -66,12 +66,12 @@ export interface NFT { isSoulbound?: boolean; /** - * Whether the NFT is currently listed for sale + * Whether the NFT is currently listed for sale. */ isOnSale?: boolean; /** - * Current owner address of the NFT + * Current owner address of the NFT. */ ownerAddress?: UserFriendlyAddress; @@ -81,12 +81,12 @@ export interface NFT { realOwnerAddress?: UserFriendlyAddress; /** - * Address of the sale contract, if the NFT is listed for sale + * Address of the sale contract, if the NFT is listed for sale. */ saleContractAddress?: UserFriendlyAddress; /** - * Off-chain metadata of the NFT (key-value pairs) + * Additional arbitrary data related to the NFT. */ extra?: { [key: string]: unknown }; } diff --git a/packages/walletkit/src/api/models/nfts/NFTAttribute.ts b/packages/walletkit/src/api/models/nfts/NFTAttribute.ts index fa45ffb15..5f34a333c 100644 --- a/packages/walletkit/src/api/models/nfts/NFTAttribute.ts +++ b/packages/walletkit/src/api/models/nfts/NFTAttribute.ts @@ -16,7 +16,7 @@ export interface NFTAttribute { traitType?: string; /** - * How the attribute should be displayed (e.g., "string", "number", "date") + * Indexer-supplied hint for how the attribute should be rendered. Optional and indexer-specific. */ displayType?: string; diff --git a/packages/walletkit/src/api/models/nfts/NFTCollection.ts b/packages/walletkit/src/api/models/nfts/NFTCollection.ts index 59f01dc88..896f33aad 100644 --- a/packages/walletkit/src/api/models/nfts/NFTCollection.ts +++ b/packages/walletkit/src/api/models/nfts/NFTCollection.ts @@ -14,47 +14,47 @@ import type { UserFriendlyAddress, Hex } from '../core/Primitives'; */ export interface NFTCollection { /** - * The blockchain address of the NFT collection contract + * The blockchain address of the NFT collection contract. */ address: UserFriendlyAddress; /** - * The name of the NFT collection + * The name of the NFT collection. */ name?: string; /** - * The image representing the NFT collection + * The image representing the NFT collection. */ image?: TokenImage; /** - * A brief description of the NFT collection + * A brief description of the NFT collection. */ description?: string; /** - * The index value for the next item to be minted in the collection + * The index value for the next item to be minted in the collection. */ nextItemIndex?: string; /** - * The hash of the collection's smart contract code + * The hash of the collection's smart contract code. */ codeHash?: Hex; /** - * The hash of the collection's data in the blockchain + * The hash of the collection's data in the blockchain. */ dataHash?: Hex; /** - * The blockchain address of the collection owner + * The blockchain address of the collection owner. */ ownerAddress?: UserFriendlyAddress; /** - * Additional arbitrary data related to the NFT collection + * Additional arbitrary data related to the NFT collection. */ extra?: { [key: string]: unknown }; } diff --git a/packages/walletkit/src/api/models/nfts/NFTRawTransferRequest.ts b/packages/walletkit/src/api/models/nfts/NFTRawTransferRequest.ts index 9fb31023f..ec44ee2a0 100644 --- a/packages/walletkit/src/api/models/nfts/NFTRawTransferRequest.ts +++ b/packages/walletkit/src/api/models/nfts/NFTRawTransferRequest.ts @@ -14,7 +14,7 @@ import type { TokenAmount } from '../core/TokenAmount'; */ export interface NFTRawTransferRequest { /** - * Contract address of the NFT to transfer + * Contract address of the NFT to transfer. */ nftAddress: UserFriendlyAddress; @@ -24,7 +24,7 @@ export interface NFTRawTransferRequest { transferAmount: TokenAmount; /** - * Transfer message details + * Transfer message details. */ message: NFTRawTransferRequestMessage; } diff --git a/packages/walletkit/src/api/models/nfts/NFTTransferRequest.ts b/packages/walletkit/src/api/models/nfts/NFTTransferRequest.ts index 946024f80..17e01d689 100644 --- a/packages/walletkit/src/api/models/nfts/NFTTransferRequest.ts +++ b/packages/walletkit/src/api/models/nfts/NFTTransferRequest.ts @@ -14,7 +14,7 @@ import type { TokenAmount } from '../core/TokenAmount'; */ export interface NFTTransferRequest { /** - * Contract address of the NFT to transfer + * Contract address of the NFT to transfer. */ nftAddress: UserFriendlyAddress; @@ -24,12 +24,12 @@ export interface NFTTransferRequest { transferAmount?: TokenAmount; /** - * Recipient wallet address + * Recipient wallet address. */ recipientAddress: UserFriendlyAddress; /** - * Human-readable comment attached to the transfer + * Human-readable comment attached to the transfer. */ comment?: string; } diff --git a/packages/walletkit/src/api/models/nfts/NFTsRequest.ts b/packages/walletkit/src/api/models/nfts/NFTsRequest.ts index 6cc4da43a..32e8ca30d 100644 --- a/packages/walletkit/src/api/models/nfts/NFTsRequest.ts +++ b/packages/walletkit/src/api/models/nfts/NFTsRequest.ts @@ -13,11 +13,11 @@ import type { Pagination, UserFriendlyAddress } from '../core/Primitives'; */ export interface NFTsRequest { /** - * NFT address to filter by + * NFT address to filter by. */ address?: UserFriendlyAddress; /** - * Pagination information + * Pagination information. */ pagination?: Pagination; } diff --git a/packages/walletkit/src/api/models/nfts/NFTsResponse.ts b/packages/walletkit/src/api/models/nfts/NFTsResponse.ts index f80d91a4d..9edfa4ee5 100644 --- a/packages/walletkit/src/api/models/nfts/NFTsResponse.ts +++ b/packages/walletkit/src/api/models/nfts/NFTsResponse.ts @@ -14,11 +14,11 @@ import type { NFT } from './NFT'; */ export interface NFTsResponse { /** - * Address book entries related to the NFTs + * Address book entries related to the NFTs. */ addressBook?: AddressBook; /** - * List of NFTs + * List of NFTs. */ nfts: NFT[]; } diff --git a/packages/walletkit/src/api/models/nfts/UserNFTsRequest.ts b/packages/walletkit/src/api/models/nfts/UserNFTsRequest.ts index a7738cd6a..597121e5e 100644 --- a/packages/walletkit/src/api/models/nfts/UserNFTsRequest.ts +++ b/packages/walletkit/src/api/models/nfts/UserNFTsRequest.ts @@ -13,11 +13,11 @@ import type { Pagination, UserFriendlyAddress } from '../core/Primitives'; */ export interface UserNFTsRequest { /** - * Owner address of the NFTs + * Owner address of the NFTs. */ ownerAddress: UserFriendlyAddress; /** - * Pagination information + * Pagination information. */ pagination?: Pagination; } diff --git a/packages/walletkit/src/api/models/onramp/OnrampLimits.ts b/packages/walletkit/src/api/models/onramp/OnrampLimits.ts index 7a8f58dc6..52c97160b 100644 --- a/packages/walletkit/src/api/models/onramp/OnrampLimits.ts +++ b/packages/walletkit/src/api/models/onramp/OnrampLimits.ts @@ -7,31 +7,31 @@ */ /** - * Onramp limits specify the boundaries of what a user can purchase + * Onramp limits specify the boundaries of what a user can purchase. */ export interface OnrampLimits { /** - * Minimum fiat amount allowed + * Minimum fiat amount allowed. */ minBaseAmount: number; /** - * Maximum fiat amount allowed + * Maximum fiat amount allowed. */ maxBaseAmount: number; /** - * Minimum crypto amount allowed + * Minimum crypto amount allowed. */ minQuoteAmount?: number; /** - * Maximum crypto amount allowed + * Maximum crypto amount allowed. */ maxQuoteAmount?: number; /** - * Provider identifier + * Provider identifier. */ providerId: string; } diff --git a/packages/walletkit/src/api/models/onramp/OnrampParams.ts b/packages/walletkit/src/api/models/onramp/OnrampParams.ts index f676f1d11..6881dec71 100644 --- a/packages/walletkit/src/api/models/onramp/OnrampParams.ts +++ b/packages/walletkit/src/api/models/onramp/OnrampParams.ts @@ -10,16 +10,16 @@ import type { UserFriendlyAddress } from '../core/Primitives'; import type { OnrampQuote } from './OnrampQuote'; /** - * Parameters for building an onramp URL + * Parameters for building an onramp URL. */ export interface OnrampParams { /** - * The onramp quote to base the transaction on + * The onramp quote to base the transaction on. */ quote: OnrampQuote; /** - * Address of the user receiving the crypto + * Address of the user receiving the crypto. */ userAddress: UserFriendlyAddress; @@ -29,7 +29,7 @@ export interface OnrampParams { redirectUrl?: string; /** - * Provider-specific options + * Provider-specific options. */ providerOptions?: TProviderOptions; } diff --git a/packages/walletkit/src/api/models/onramp/OnrampQuote.ts b/packages/walletkit/src/api/models/onramp/OnrampQuote.ts index 91e9b7245..6c592c59f 100644 --- a/packages/walletkit/src/api/models/onramp/OnrampQuote.ts +++ b/packages/walletkit/src/api/models/onramp/OnrampQuote.ts @@ -7,7 +7,7 @@ */ /** - * Onramp quote response with pricing information + * Onramp quote response with pricing information. */ export interface OnrampQuote { /** @@ -21,12 +21,12 @@ export interface OnrampQuote { cryptoCurrency: string; /** - * Amount of fiat to spend + * Amount of fiat to spend. */ fiatAmount: string; /** - * Amount of crypto to receive + * Amount of crypto to receive. */ cryptoAmount: string; @@ -46,12 +46,12 @@ export interface OnrampQuote { networkFeeFiat?: string; /** - * Identifier of the onramp provider + * Identifier of the onramp provider. */ providerId: string; /** - * Provider-specific metadata for the quote + * Provider-specific metadata for the quote. */ metadata?: unknown; } diff --git a/packages/walletkit/src/api/models/onramp/OnrampQuoteParams.ts b/packages/walletkit/src/api/models/onramp/OnrampQuoteParams.ts index 63a3b3bc5..52db78e07 100644 --- a/packages/walletkit/src/api/models/onramp/OnrampQuoteParams.ts +++ b/packages/walletkit/src/api/models/onramp/OnrampQuoteParams.ts @@ -9,7 +9,7 @@ import type { Network } from '../core/Network'; /** - * Base parameters for requesting an onramp quote + * Base parameters for requesting an onramp quote. */ export interface OnrampQuoteParams { /** @@ -28,12 +28,12 @@ export interface OnrampQuoteParams { cryptoCurrency: string; /** - * Network on which the crypto will be received + * Network on which the crypto will be received. */ network?: Network; /** - * Provider-specific options + * Provider-specific options. */ providerOptions?: TProviderOptions; diff --git a/packages/walletkit/src/api/models/sessions/TONConnectSession.ts b/packages/walletkit/src/api/models/sessions/TONConnectSession.ts index 5935c6982..ae2fdad34 100644 --- a/packages/walletkit/src/api/models/sessions/TONConnectSession.ts +++ b/packages/walletkit/src/api/models/sessions/TONConnectSession.ts @@ -20,12 +20,12 @@ export interface TONConnectSession { domain: string; /** - * Display name of the dApp + * Display name of the dApp. */ dAppName?: string; /** - * Brief description of the dApp's purpose + * Brief description of the dApp's purpose. */ dAppDescription?: string; diff --git a/packages/walletkit/src/api/models/staking/StakeParams.ts b/packages/walletkit/src/api/models/staking/StakeParams.ts index 8a59e9f1d..89f8e9513 100644 --- a/packages/walletkit/src/api/models/staking/StakeParams.ts +++ b/packages/walletkit/src/api/models/staking/StakeParams.ts @@ -10,21 +10,21 @@ import type { UserFriendlyAddress } from '../core/Primitives'; import type { StakingQuote } from './StakingQuote'; /** - * Parameters for staking TON + * Parameters for staking TON. */ export interface StakeParams { /** - * The staking quote based on which the transaction is built + * The staking quote based on which the transaction is built. */ quote: StakingQuote; /** - * Address of the user performing the staking + * Address of the user performing the staking. */ userAddress: UserFriendlyAddress; /** - * Provider-specific options + * Provider-specific options. */ providerOptions?: TProviderOptions; } diff --git a/packages/walletkit/src/api/models/staking/StakingBalance.ts b/packages/walletkit/src/api/models/staking/StakingBalance.ts index c99f35a6f..d5d34dc06 100644 --- a/packages/walletkit/src/api/models/staking/StakingBalance.ts +++ b/packages/walletkit/src/api/models/staking/StakingBalance.ts @@ -9,31 +9,31 @@ import type { TokenAmount } from '../core/TokenAmount'; /** - * Staking balance information for a user + * Staking balance information for a user. */ export interface StakingBalance { /** - * Amount currently staked + * Amount currently staked, in raw smallest units of the stake token (e.g., nano-TON). */ rawStakedBalance: TokenAmount; /** - * Amount currently staked + * Amount currently staked, formatted to the stake token's decimals as a human-readable decimal string (e.g., `"12.5"`). */ stakedBalance: string; /** - * Amount available for instant unstake + * Amount available for instant unstake, in raw smallest units of the stake token (e.g., nano-TON). */ rawInstantUnstakeAvailable: TokenAmount; /** - * Amount available for instant unstake + * Amount available for instant unstake, formatted to the stake token's decimals as a human-readable decimal string (e.g., `"12.5"`). */ instantUnstakeAvailable: string; /** - * Identifier of the staking provider + * Identifier of the staking provider. */ providerId: string; } diff --git a/packages/walletkit/src/api/models/staking/StakingProviderInfo.ts b/packages/walletkit/src/api/models/staking/StakingProviderInfo.ts index 4f3a10032..f153bc335 100644 --- a/packages/walletkit/src/api/models/staking/StakingProviderInfo.ts +++ b/packages/walletkit/src/api/models/staking/StakingProviderInfo.ts @@ -9,7 +9,7 @@ import type { TokenAmount } from '../core/TokenAmount'; /** - * Dynamic staking information for a provider + * Dynamic staking information for a provider. */ export interface StakingProviderInfo { /** @@ -18,12 +18,12 @@ export interface StakingProviderInfo { apy: number; /** - * Amount available for instant unstake + * Amount available for instant unstake right now, in raw smallest units of the stake token (e.g., nano-TON). */ rawInstantUnstakeAvailable?: TokenAmount; /** - * Amount available for instant unstake + * Amount available for instant unstake right now, formatted to the stake token's decimals as a human-readable decimal string (e.g., `"12.5"`). */ instantUnstakeAvailable?: string; diff --git a/packages/walletkit/src/api/models/staking/StakingProviderMetadata.ts b/packages/walletkit/src/api/models/staking/StakingProviderMetadata.ts index 33d08c996..f51c8ca48 100644 --- a/packages/walletkit/src/api/models/staking/StakingProviderMetadata.ts +++ b/packages/walletkit/src/api/models/staking/StakingProviderMetadata.ts @@ -10,21 +10,25 @@ import type { UserFriendlyAddress } from '../core/Primitives'; import type { UnstakeModes } from './UnstakeMode'; export interface StakingTokenInfo { + /** Ticker symbol (e.g., `"TON"`, `"tsTON"`). */ ticker: string; - /** @format int */ + /** + * Number of decimal places used to format raw amounts. + * @format int + */ decimals: number; - /** 'ton' for native TON, otherwise contract address in friendly format */ + /** `'ton'` for native TON, otherwise the token contract address in user-friendly format. */ address: string; } /** - * Static metadata for a staking provider + * Static metadata for a staking provider. */ export interface StakingProviderMetadata { /** Human-readable provider name (e.g. "Tonstakers") */ name: string; - /** Supported unstake modes for this provider */ + /** Supported unstake modes for this provider. */ supportedUnstakeModes: UnstakeModes[]; /** Whether provider supports reversed quote format (e.g., passing TON instead of tsTON for unstake) */ @@ -41,13 +45,19 @@ export interface StakingProviderMetadata { } /** - * Used in provider configuration to override fields of the provider's metadata. + * Partial overrides applied on top of a provider's built-in {@link StakingProviderMetadata}. Used in provider configuration (e.g. `TonStakersChainConfig.metadata`) when an integrator needs to tweak the display name, token info or supported modes for a specific chain. */ export interface StakingProviderMetadataOverride { + /** Override the human-readable provider name surfaced in UIs. */ name?: string; + /** Override the {@link StakingTokenInfo} of the token the user sends when staking. */ stakeToken?: StakingTokenInfo; + /** Override the {@link StakingTokenInfo} of the token the user receives when staking (e.g. liquid-staking receipt). */ receiveToken?: StakingTokenInfo; + /** Override the provider contract address (user-friendly format). */ contractAddress?: UserFriendlyAddress; + /** Override the list of supported unstake-timing modes. See {@link UnstakeMode}. */ supportedUnstakeModes?: UnstakeModes[]; + /** Override whether the provider supports reversed-amount quotes (e.g., specifying TON instead of tsTON on an unstake quote). */ supportsReversedQuote?: boolean; } diff --git a/packages/walletkit/src/api/models/staking/StakingQuote.ts b/packages/walletkit/src/api/models/staking/StakingQuote.ts index 13ab80dec..aecbf7cb6 100644 --- a/packages/walletkit/src/api/models/staking/StakingQuote.ts +++ b/packages/walletkit/src/api/models/staking/StakingQuote.ts @@ -12,7 +12,7 @@ import type { StakingQuoteDirection } from './StakingQuoteDirection'; import type { UnstakeModes } from './UnstakeMode'; /** - * Staking quote response with pricing information + * Staking quote response with pricing information. */ export interface StakingQuote { /** @@ -21,42 +21,42 @@ export interface StakingQuote { direction: StakingQuoteDirection; /** - * Amount of tokens being provided + * Amount of tokens being provided. */ rawAmountIn: TokenAmount; /** - * Estimated amount of tokens to be received + * Estimated amount of tokens to be received. */ rawAmountOut: TokenAmount; /** - * Formatted amount of tokens being provided + * Formatted amount of tokens being provided. */ amountIn: string; /** - * Formatted estimated amount of tokens to be received + * Formatted estimated amount of tokens to be received. */ amountOut: string; /** - * Network on which the staking will be executed + * Network on which the staking will be executed. */ network: Network; /** - * Identifier of the staking provider + * Identifier of the staking provider. */ providerId: string; /** - * Mode of unstaking (if applicable) + * Unstake-timing mode the quote was produced for. Only meaningful when `direction === 'unstake'` — for `'stake'` it is ignored. */ unstakeMode?: UnstakeModes; /** - * Provider-specific metadata for the quote + * Provider-specific metadata for the quote. */ metadata?: unknown; } diff --git a/packages/walletkit/src/api/models/staking/StakingQuoteDirection.ts b/packages/walletkit/src/api/models/staking/StakingQuoteDirection.ts index ca2625b77..1782cc963 100644 --- a/packages/walletkit/src/api/models/staking/StakingQuoteDirection.ts +++ b/packages/walletkit/src/api/models/staking/StakingQuoteDirection.ts @@ -7,6 +7,6 @@ */ /** - * Direction of the staking quote + * Direction of the staking quote. */ export type StakingQuoteDirection = 'stake' | 'unstake'; diff --git a/packages/walletkit/src/api/models/staking/StakingQuoteParams.ts b/packages/walletkit/src/api/models/staking/StakingQuoteParams.ts index 58a095e87..4b4d79041 100644 --- a/packages/walletkit/src/api/models/staking/StakingQuoteParams.ts +++ b/packages/walletkit/src/api/models/staking/StakingQuoteParams.ts @@ -12,7 +12,7 @@ import type { StakingQuoteDirection } from './StakingQuoteDirection'; import type { UnstakeModes } from './UnstakeMode'; /** - * Parameters for getting a staking quote + * Parameters for getting a staking quote. */ export interface StakingQuoteParams { /** @@ -21,22 +21,22 @@ export interface StakingQuoteParams { direction: StakingQuoteDirection; /** - * Amount of tokens to stake or unstake + * Amount of tokens to stake or unstake. */ amount: string; /** - * Address of the user + * Address of the user. */ userAddress?: UserFriendlyAddress; /** - * Network on which the staking will be executed + * Network on which the staking will be executed. */ network?: Network; /** - * Requested mode of unstaking + * Unstake-timing mode the quote should target — see {@link UnstakeMode} for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. */ unstakeMode?: UnstakeModes; @@ -47,7 +47,7 @@ export interface StakingQuoteParams { isReversed?: boolean; /** - * Provider-specific options + * Provider-specific options. */ providerOptions?: TProviderOptions; } diff --git a/packages/walletkit/src/api/models/staking/UnstakeMode.ts b/packages/walletkit/src/api/models/staking/UnstakeMode.ts index cda5eaf3b..8ddd11aad 100644 --- a/packages/walletkit/src/api/models/staking/UnstakeMode.ts +++ b/packages/walletkit/src/api/models/staking/UnstakeMode.ts @@ -17,6 +17,6 @@ export const UnstakeMode = { } as const; /** - * Mode of unstaking + * Union of {@link UnstakeMode} values. Carried on {@link StakingQuoteParams}'s `unstakeMode` and on {@link StakingProviderMetadata}'s `supportedUnstakeModes` to discriminate `'INSTANT'` / `'WHEN_AVAILABLE'` / `'ROUND_END'` flows. */ export type UnstakeModes = (typeof UnstakeMode)[keyof typeof UnstakeMode]; diff --git a/packages/walletkit/src/api/models/streaming/BalanceUpdate.ts b/packages/walletkit/src/api/models/streaming/BalanceUpdate.ts index 44f4f2fb1..4ab11159d 100644 --- a/packages/walletkit/src/api/models/streaming/BalanceUpdate.ts +++ b/packages/walletkit/src/api/models/streaming/BalanceUpdate.ts @@ -11,12 +11,12 @@ import type { StreamingBaseUpdate } from './StreamingBaseUpdate'; import type { TokenAmount } from '../core/TokenAmount'; export interface BalanceUpdate extends StreamingBaseUpdate { - /** The update type field */ + /** The update type field. */ type: 'balance'; - /** The account address */ + /** The account address. */ address: UserFriendlyAddress; - /** The account balance in nano units */ + /** The account balance in nano units. */ rawBalance: TokenAmount; - /** The formatted balance */ + /** The formatted balance. */ balance: string; } diff --git a/packages/walletkit/src/api/models/streaming/JettonUpdate.ts b/packages/walletkit/src/api/models/streaming/JettonUpdate.ts index ee5f236e1..0eada298d 100644 --- a/packages/walletkit/src/api/models/streaming/JettonUpdate.ts +++ b/packages/walletkit/src/api/models/streaming/JettonUpdate.ts @@ -11,13 +11,13 @@ import type { StreamingBaseUpdate } from './StreamingBaseUpdate'; import type { TokenAmount } from '../core/TokenAmount'; export interface JettonUpdate extends StreamingBaseUpdate { - /** The update type field */ + /** The update type field. */ type: 'jettons'; - /** The master jetton contract address */ + /** The master jetton contract address. */ masterAddress: UserFriendlyAddress; - /** The jetton wallet contract address */ + /** The jetton wallet contract address. */ walletAddress: UserFriendlyAddress; - /** The owner of the jetton wallet */ + /** The owner of the jetton wallet. */ ownerAddress: UserFriendlyAddress; /** Balance in raw smallest units (e.g. nano) */ rawBalance: TokenAmount; @@ -26,6 +26,6 @@ export interface JettonUpdate extends StreamingBaseUpdate { * @format: int */ decimals?: number; - /** Human readable formatted balance if decimals are known */ + /** Human readable formatted balance if decimals are known. */ balance?: string; } diff --git a/packages/walletkit/src/api/models/streaming/StreamingBaseUpdate.ts b/packages/walletkit/src/api/models/streaming/StreamingBaseUpdate.ts index 7cb39f3b3..65d77e037 100644 --- a/packages/walletkit/src/api/models/streaming/StreamingBaseUpdate.ts +++ b/packages/walletkit/src/api/models/streaming/StreamingBaseUpdate.ts @@ -10,8 +10,8 @@ import type { StreamingWatchType } from './StreamingWatchType'; import type { StreamingUpdateStatus } from './StreamingUpdateStatus'; export interface StreamingBaseUpdate { - /** The update type field */ + /** Discriminator identifying the kind of streaming update (`'balance'`, `'jettons'`, `'transactions'`). */ type: StreamingWatchType; - /** The finality of the update */ + /** Finality stage of the update — see {@link StreamingUpdateStatus}. */ status: StreamingUpdateStatus; } diff --git a/packages/walletkit/src/api/models/streaming/StreamingEvents.ts b/packages/walletkit/src/api/models/streaming/StreamingEvents.ts index 8d65827aa..ee532f756 100644 --- a/packages/walletkit/src/api/models/streaming/StreamingEvents.ts +++ b/packages/walletkit/src/api/models/streaming/StreamingEvents.ts @@ -11,7 +11,10 @@ import type { TransactionsUpdate } from './TransactionsUpdate'; import type { JettonUpdate } from './JettonUpdate'; export interface StreamingEvents { + /** Fired by a streaming provider when a watched address's TON balance changes. */ 'streaming:balance-update': BalanceUpdate; + /** Fired by a streaming provider when new transactions land for a watched address. */ 'streaming:transactions': TransactionsUpdate; + /** Fired by a streaming provider when a watched address's jetton holdings change. */ 'streaming:jettons-update': JettonUpdate; } diff --git a/packages/walletkit/src/api/models/streaming/TransactionsUpdate.ts b/packages/walletkit/src/api/models/streaming/TransactionsUpdate.ts index 5255694ff..a2b50521b 100644 --- a/packages/walletkit/src/api/models/streaming/TransactionsUpdate.ts +++ b/packages/walletkit/src/api/models/streaming/TransactionsUpdate.ts @@ -13,16 +13,16 @@ import type { AddressBook } from '../core/AddressBook'; import type { StreamingBaseUpdate } from './StreamingBaseUpdate'; export interface TransactionsUpdate extends StreamingBaseUpdate { - /** The update type field */ + /** Discriminator pinned to `'transactions'` — identifies this update as a transactions stream payload. */ type: 'transactions'; - /** The account address */ + /** Account address the transactions belong to (the watched address). */ address: UserFriendlyAddress; - /** The array of transactions */ + /** Transactions that landed for `address` in this update. */ transactions: Transaction[]; - /** The hash of the trace */ + /** Hash of the trace that produced these transactions — the root external-message hash that spawned them. */ traceHash: Hex; - /** Address book from streaming v2 notification */ + /** Pre-resolved address-book entries for raw addresses referenced inside `transactions`, so the UI can render labels without extra lookups. */ addressBook?: AddressBook; - /** Metadata from streaming v2 notification */ + /** Pre-fetched address metadata (interfaces, domain) for the watched `address`. */ metadata?: TransactionAddressMetadata; } diff --git a/packages/walletkit/src/api/models/swaps/SwapParams.ts b/packages/walletkit/src/api/models/swaps/SwapParams.ts index 4b877ef72..3e24825a6 100644 --- a/packages/walletkit/src/api/models/swaps/SwapParams.ts +++ b/packages/walletkit/src/api/models/swaps/SwapParams.ts @@ -10,16 +10,16 @@ import type { UserFriendlyAddress } from '../core/Primitives'; import type { SwapQuote } from './SwapQuote'; /** - * Parameters for building swap transaction + * Parameters for building swap transaction. */ export interface SwapParams { /** - * The swap quote based on which the transaction is built + * The swap quote based on which the transaction is built. */ quote: SwapQuote; /** - * Address of the user performing the swap + * Address of the user performing the swap. */ userAddress: UserFriendlyAddress; @@ -35,13 +35,13 @@ export interface SwapParams { slippageBps?: number; /** - * Transaction deadline in unix timestamp + * Unix timestamp (in seconds) after which the swap transaction must not be executed. * @format int */ deadline?: number; /** - * Provider-specific options + * Provider-specific options. */ providerOptions?: TProviderOptions; } diff --git a/packages/walletkit/src/api/models/swaps/SwapQuote.ts b/packages/walletkit/src/api/models/swaps/SwapQuote.ts index 227755f97..2181db528 100644 --- a/packages/walletkit/src/api/models/swaps/SwapQuote.ts +++ b/packages/walletkit/src/api/models/swaps/SwapQuote.ts @@ -11,51 +11,51 @@ import type { TokenAmount } from '../core/TokenAmount'; import type { SwapToken } from './SwapToken'; /** - * Swap quote response with pricing information + * Swap quote response with pricing information. */ export interface SwapQuote { /** - * Token being sold + * Token being sold. */ fromToken: SwapToken; /** - * Token being bought + * Token being bought. */ toToken: SwapToken; /** - * Amount of tokens to sell + * Amount of `fromToken` to sell, in raw smallest units (e.g., nano-TON). */ rawFromAmount: TokenAmount; /** - * Amount of tokens to buy + * Amount of `toToken` to buy, in raw smallest units (e.g., nano-TON). */ rawToAmount: TokenAmount; /** - * Amount of tokens to sell + * Amount of `fromToken` to sell, formatted to the token's decimals as a human-readable decimal string (e.g., `"1.5"`). */ fromAmount: string; /** - * Amount of tokens to buy + * Amount of `toToken` to buy, formatted to the token's decimals as a human-readable decimal string (e.g., `"1.5"`). */ toAmount: string; /** - * Minimum amount of tokens to receive (after slippage) + * Minimum amount of `toToken` to receive after slippage, in raw smallest units (e.g., nano-TON). */ rawMinReceived: TokenAmount; /** - * Minimum amount of tokens to receive (after slippage) + * Minimum amount of `toToken` to receive after slippage, formatted to the token's decimals as a human-readable decimal string (e.g., `"1.5"`). */ minReceived: string; /** - * Network on which the swap will be executed + * Network on which the swap will be executed. */ network: Network; @@ -66,7 +66,7 @@ export interface SwapQuote { priceImpact?: number; /** - * Identifier of the swap provider + * Identifier of the swap provider. */ providerId: string; @@ -77,7 +77,7 @@ export interface SwapQuote { expiresAt?: number; /** - * Provider-specific metadata for the quote + * Provider-specific metadata for the quote. */ metadata?: unknown; } diff --git a/packages/walletkit/src/api/models/swaps/SwapQuoteParams.ts b/packages/walletkit/src/api/models/swaps/SwapQuoteParams.ts index 41549571c..5ef9e9467 100644 --- a/packages/walletkit/src/api/models/swaps/SwapQuoteParams.ts +++ b/packages/walletkit/src/api/models/swaps/SwapQuoteParams.ts @@ -10,7 +10,7 @@ import type { Network } from '../core/Network'; import type { SwapToken } from './SwapToken'; /** - * Base parameters for requesting a swap quote + * Base parameters for requesting a swap quote. */ export interface SwapQuoteParams { /** @@ -19,17 +19,17 @@ export interface SwapQuoteParams { amount: string; /** - * Token to swap from + * Token to swap from. */ from: SwapToken; /** - * Token to swap to + * Token to swap to. */ to: SwapToken; /** - * Network on which the swap will be executed + * Network on which the swap will be executed. */ network: Network; @@ -46,7 +46,7 @@ export interface SwapQuoteParams { maxOutgoingMessages?: number; /** - * Provider-specific options + * Provider-specific options. */ providerOptions?: TProviderOptions; diff --git a/packages/walletkit/src/api/models/swaps/SwapToken.ts b/packages/walletkit/src/api/models/swaps/SwapToken.ts index 7bdd2c1c7..3c72e231c 100644 --- a/packages/walletkit/src/api/models/swaps/SwapToken.ts +++ b/packages/walletkit/src/api/models/swaps/SwapToken.ts @@ -7,18 +7,24 @@ */ /** - * Token type for swap + * Token type for swap. */ export type SwapToken = { + /** Token contract address. `'ton'` is used for native TON on the TON chain. */ address: string; /** + * Number of decimal places used to format raw amounts. * @format: int */ decimals: number; + /** Display name (e.g., `"Tether USD"`). */ name?: string; + /** Ticker symbol (e.g., `"USDT"`). */ symbol?: string; + /** URL of the token's image. */ image?: string; + /** Chain id in CAIP-2 format when the token lives outside TON. */ chainId?: string; }; diff --git a/packages/walletkit/src/api/models/tons/TONTransferRequest.ts b/packages/walletkit/src/api/models/tons/TONTransferRequest.ts index 917c37f02..557a753bd 100644 --- a/packages/walletkit/src/api/models/tons/TONTransferRequest.ts +++ b/packages/walletkit/src/api/models/tons/TONTransferRequest.ts @@ -16,12 +16,12 @@ import type { SendMode } from '../core/SendMode'; */ export interface TONTransferRequest { /** - * Amount to transfer in nanotons + * Amount to transfer in nanotons. */ transferAmount: TokenAmount; /** - * Recipient address in user-friendly format + * Recipient address in user-friendly format. */ recipientAddress: UserFriendlyAddress; @@ -31,12 +31,12 @@ export interface TONTransferRequest { mode?: SendMode; /** - * Additional currencies to include in the transfer + * Additional currencies to include in the transfer. */ extraCurrency?: ExtraCurrencies; /** - * Initial state for deploying a new contract, encoded in Base64 + * Initial state for deploying a new contract, encoded in Base64. */ stateInit?: Base64String; @@ -46,7 +46,7 @@ export interface TONTransferRequest { payload?: Base64String; /** - * Human-readable text comment attached to the transfer + * Human-readable text comment attached to the transfer. */ comment?: string; } diff --git a/packages/walletkit/src/api/models/transactions/SendTransactionResponse.ts b/packages/walletkit/src/api/models/transactions/SendTransactionResponse.ts index 0f242103e..712af539c 100644 --- a/packages/walletkit/src/api/models/transactions/SendTransactionResponse.ts +++ b/packages/walletkit/src/api/models/transactions/SendTransactionResponse.ts @@ -10,15 +10,15 @@ import type { Base64String, Hex } from '../core/Primitives'; export interface SendTransactionResponse { /** - * BOC of the sent transaction + * BoC of the sent transaction. */ boc: Base64String; /** - * Normalized BOC of the external-in message + * Normalized BoC of the external-in message. */ normalizedBoc: Base64String; /** - * Hash of the normalized external-in message + * Hash of the normalized external-in message. */ normalizedHash: Hex; } diff --git a/packages/walletkit/src/api/models/transactions/Transaction.ts b/packages/walletkit/src/api/models/transactions/Transaction.ts index 9634bc1e9..6861524f9 100644 --- a/packages/walletkit/src/api/models/transactions/Transaction.ts +++ b/packages/walletkit/src/api/models/transactions/Transaction.ts @@ -15,37 +15,37 @@ import type { TokenAmount } from '../core/TokenAmount'; */ export interface Transaction { /** - * Account of the transaction + * Account of the transaction. */ account: UserFriendlyAddress; /** - * The state of the account before the transaction was executed + * The state of the account before the transaction was executed. */ accountStateBefore?: AccountState; /** - * * The state of the account after the transaction has been applied + * The state of the account after the transaction has been applied. */ accountStateAfter?: AccountState; /** - * The detailed breakdown of the transaction execution + * The detailed breakdown of the transaction execution. */ description?: TransactionDescription; /** - * Hash of the transaction + * Hash of the transaction. */ hash: Hex; /** - * The logical time of the transaction + * The logical time of the transaction. */ logicalTime: LogicalTime; /** - * Unix timestamp of the transaction + * Unix timestamp of the transaction. */ now: number; @@ -56,62 +56,62 @@ export interface Transaction { mcBlockSeqno: number; /** - * External hash of the trace + * External hash of the trace. */ traceExternalHash: Hex; /** - * ID of the trace + * ID of the trace. */ traceId?: string; /** - * The hash of the previous transaction + * The hash of the previous transaction. */ previousTransactionHash?: string; /** - * The logical time of the previous transaction + * The logical time of the previous transaction. */ previousTransactionLogicalTime?: LogicalTime; /** - * Original status of the transaction + * Original status of the transaction. */ origStatus?: AccountStatus; /** - * End status of the transaction + * End status of the transaction. */ endStatus?: AccountStatus; /** - * Total fees of the transaction + * Total fees of the transaction. */ totalFees?: TokenAmount; /** - * Extra currencies in the total fees + * Extra currencies in the total fees. */ totalFeesExtraCurrencies?: ExtraCurrencies; /** - * The reference to the block in which the transaction was included + * The reference to the block in which the transaction was included. */ blockRef?: TransactionBlockRef; /** - * The incoming message associated with the transaction + * The incoming message associated with the transaction. */ inMessage?: TransactionMessage; /** - * The list of outgoing messages produced by the transaction + * The list of outgoing messages produced by the transaction. */ outMessages: TransactionMessage[]; /** - * Emulated state of the transaction + * Emulated state of the transaction. */ isEmulated: boolean; } @@ -130,37 +130,37 @@ export type AccountStatus = */ export interface AccountState { /** - * The state hash of the account + * The state hash of the account. */ hash?: string; /** - * The account's balance in nanotons + * The account's balance in nanotons. */ balance: TokenAmount; /** - * The additional currencies held by the account, if any + * The additional currencies held by the account, if any. */ extraCurrencies?: ExtraCurrencies; /** - * The status of the account + * The status of the account. */ accountStatus?: AccountStatus; /** - * The hash of the frozen account state, if the account is frozen + * The hash of the frozen account state, if the account is frozen. */ frozenHash?: string; /** - * The hash of the contract's data section + * The hash of the contract's data section. */ dataHash?: string; /** - * The hash of the smart contract code + * The hash of the smart contract code. */ codeHash?: string; } @@ -176,7 +176,7 @@ export interface TransactionBlockRef { workchain: number; /** - * The shard identifier of the block + * The shard identifier of the block. */ shard: string; @@ -192,52 +192,52 @@ export interface TransactionBlockRef { */ export interface TransactionMessage { /** - * The base64-encoded hash of the message + * The base64-encoded hash of the message. */ hash: Hex; /** - * The normalized version of the message hash + * The normalized version of the message hash. */ normalizedHash?: Hex; /** - * The source address of the message + * The source address of the message. */ source?: UserFriendlyAddress; /** - * The destination address of the message + * The destination address of the message. */ destination?: UserFriendlyAddress; /** - * The amount of nanos transferred with the message + * The amount of nanos transferred with the message. */ value?: TokenAmount; /** - * The additional currencies included in the message + * The additional currencies included in the message. */ valueExtraCurrencies?: ExtraCurrencies; /** - * The forwarding fee for the message + * The forwarding fee for the message. */ fwdFee?: TokenAmount; /** - * The logical time when the message was created + * The logical time when the message was created. */ creationLogicalTime?: LogicalTime; /** - * The timestamp when the message was created + * The timestamp when the message was created. */ createdAt?: number; /** - * The opcode included in the message payload + * The opcode included in the message payload. */ opcode?: string; @@ -248,17 +248,17 @@ export interface TransactionMessage { ihrDisabled?: boolean; /** - * The fee for IHR delivery + * The fee for IHR delivery. */ ihrFee?: TokenAmount; /** - * The flag indicating if the message requested a bounce on failure + * The flag indicating if the message requested a bounce on failure. */ isBounce?: boolean; /** - * The flag indicating if the message was bounced back + * The flag indicating if the message was bounced back. */ isBounced?: boolean; @@ -268,7 +268,7 @@ export interface TransactionMessage { importFee?: TokenAmount; /** - * The content body of the message + * The content body of the message. */ messageContent?: TransactionMessageContent; } @@ -278,17 +278,17 @@ export interface TransactionMessage { */ export interface TransactionMessageContent { /** - * The hash of the initial state + * The hash of the initial state. */ hash?: string; /** - * The body in BOC format + * The body in BoC format. */ body?: Base64String; /** - * The decoded metadata from the initial state body + * The decoded metadata from the initial state body. */ decoded?: unknown; } @@ -303,47 +303,47 @@ export interface TransactionDescription { type: string; /** - * The flag indicating if the transaction was aborted + * The flag indicating if the transaction was aborted. */ isAborted: boolean; /** - * The flag indicating if the account was destroyed + * The flag indicating if the account was destroyed. */ isDestroyed: boolean; /** - * The flag indicating if the credit phase was executed first + * The flag indicating if the credit phase was executed first. */ isCreditFirst: boolean; /** - * The flag indicating if this was a tock transaction + * The flag indicating if this was a tock transaction. */ isTock: boolean; /** - * The flag indicating if the contract was installed + * The flag indicating if the contract was installed. */ isInstalled: boolean; /** - * The storage phase data of the transaction + * The storage phase data of the transaction. */ storagePhase?: TransactionStoragePhase; /** - * The credit phase of the transaction + * The credit phase of the transaction. */ creditPhase?: TransactionCreditPhase; /** - * The compute phase data of the transaction + * The compute phase data of the transaction. */ computePhase?: TransactionComputePhase; /** - * The action phase data of the transaction + * The action phase data of the transaction. */ action?: TransactionAction; } @@ -353,12 +353,12 @@ export interface TransactionDescription { */ export interface TransactionStoragePhase { /** - * The storage fees collected during this phase + * The storage fees collected during this phase. */ storageFeesCollected: TokenAmount; /** - * The status change applied to the account during the storage phase + * The status change applied to the account during the storage phase. */ statusChange?: string; } @@ -368,7 +368,7 @@ export interface TransactionStoragePhase { */ export interface TransactionCreditPhase { /** - * The credited amount + * The credited amount. */ credit?: TokenAmount; } @@ -378,42 +378,42 @@ export interface TransactionCreditPhase { */ export interface TransactionComputePhase { /** - * The flag indicating if the compute phase was skipped + * The flag indicating if the compute phase was skipped. */ isSkipped?: boolean; /** - * The success state of the compute phase + * The success state of the compute phase. */ isSuccess?: boolean; /** - * The flag indicating if message state was used + * The flag indicating if message state was used. */ isMessageStateUsed?: boolean; /** - * The flag indicating if the account was activated during compute + * The flag indicating if the account was activated during compute. */ isAccountActivated?: boolean; /** - * The gas fees charged for compute + * The gas fees charged for compute. */ gasFees?: TokenAmount; /** - * The total gas used in the compute phase + * The total gas used in the compute phase. */ gasUsed?: TokenAmount; /** - * The gas limit for the compute phase + * The gas limit for the compute phase. */ gasLimit?: TokenAmount; /** - * The gas credit for the compute phase + * The gas credit for the compute phase. */ gasCredit?: TokenAmount; @@ -436,12 +436,12 @@ export interface TransactionComputePhase { vmStepsNumber?: number; /** - * The hash of the initial VM state before compute + * The hash of the initial VM state before compute. */ vmInitStateHash?: Hex; /** - * The hash of the final VM state after compute + * The hash of the final VM state after compute. */ vmFinalStateHash?: Hex; } @@ -451,32 +451,32 @@ export interface TransactionComputePhase { */ export interface TransactionAction { /** - * The flag indicating whether the action phase succeeded + * The flag indicating whether the action phase succeeded. */ isSuccess?: boolean; /** - * The flag indicating whether the action phase was valid + * The flag indicating whether the action phase was valid. */ isValid?: boolean; /** - * The flag indicating if the transaction had insufficient funds + * The flag indicating if the transaction had insufficient funds. */ hasNoFunds?: boolean; /** - * The status change applied to the account during the action phase + * The status change applied to the account during the action phase. */ statusChange?: string; /** - * The total forwarding fees charged + * The total forwarding fees charged. */ totalForwardingFees?: TokenAmount; /** - * The total fees charged for actions + * The total fees charged for actions. */ totalActionFees?: TokenAmount; @@ -511,12 +511,12 @@ export interface TransactionAction { messagesCreatedNumber?: number; /** - * The hash of the action list + * The hash of the action list. */ actionListHash?: Hex; /** - * The total size of messages created in the action phase + * The total size of messages created in the action phase. */ totalMessagesSize?: TransactionActionMessageSize; } @@ -526,12 +526,12 @@ export interface TransactionAction { */ export interface TransactionActionMessageSize { /** - * The total number of cells used + * The total number of cells used. */ cells?: string; /** - * The total number of bits used + * The total number of bits used. */ bits?: string; } diff --git a/packages/walletkit/src/api/models/transactions/TransactionMetadata.ts b/packages/walletkit/src/api/models/transactions/TransactionMetadata.ts index d77daccbb..f24a9e3d8 100644 --- a/packages/walletkit/src/api/models/transactions/TransactionMetadata.ts +++ b/packages/walletkit/src/api/models/transactions/TransactionMetadata.ts @@ -22,7 +22,7 @@ export type TransactionAddressMetadata = { */ export interface TransactionAddressMetadataEntry { /** - * Token information associated with this address, if any + * Token information associated with this address, if any. */ tokenInfo?: TransactionTokenInfo[]; } @@ -40,15 +40,15 @@ export type TransactionTokenInfo = */ export interface TransactionTokenInfoBase { /** - * Indicates if the token contract is valid + * Indicates if the token contract is valid. */ isValid: boolean; /** - * Type of token + * Type of token. */ type: string; /** - * Additional metadata for the token, such as image sizes, decimal precision, external links, and marketplaces + * Additional metadata for the token, such as image sizes, decimal precision, external links, and marketplaces. */ extra: { [key: string]: unknown }; } @@ -58,15 +58,15 @@ export interface TransactionTokenInfoBase { */ export interface TransactionTokenInfoJettonWallets extends TransactionTokenInfoBase { /** - * Current balance of the Jetton wallet + * Current balance of the Jetton wallet. */ balance: TokenAmount; /** - * Address of the Jetton master contract + * Address of the Jetton master contract. */ jetton: UserFriendlyAddress; /** - * Owner address of this Jetton wallet + * Owner address of this Jetton wallet. */ owner: UserFriendlyAddress; } @@ -76,15 +76,15 @@ export interface TransactionTokenInfoJettonWallets extends TransactionTokenInfoB */ export interface TransactionTokenInfoJettonMasters extends TransactionTokenInfoBase { /** - * Display name of the Jetton + * Display name of the Jetton. */ name: string; /** - * Ticker symbol of the Jetton + * Ticker symbol of the Jetton. */ symbol: string; /** - * Human-readable description of the Jetton + * Human-readable description of the Jetton. */ description: string; /** @@ -93,19 +93,19 @@ export interface TransactionTokenInfoJettonMasters extends TransactionTokenInfoB */ decimalsCount: number; /** - * Token image in various sizes + * Token image in various sizes. */ image?: TokenImage; /** - * Social media links for the Jetton project + * Social media links for the Jetton project. */ social: string[]; /** - * Metadata URI for the Jetton + * Metadata URI for the Jetton. */ uri: string; /** - * Official website URLs for the Jetton project + * Official website URLs for the Jetton project. */ websites: string[]; } diff --git a/packages/walletkit/src/api/models/transactions/TransactionRequest.ts b/packages/walletkit/src/api/models/transactions/TransactionRequest.ts index 53a1d5cf5..3146b48c3 100644 --- a/packages/walletkit/src/api/models/transactions/TransactionRequest.ts +++ b/packages/walletkit/src/api/models/transactions/TransactionRequest.ts @@ -17,17 +17,17 @@ import type { TokenAmount } from '../core/TokenAmount'; */ export interface TransactionRequest { /** - * List of messages to include in the transaction + * List of messages to include in the transaction. */ messages: TransactionRequestMessage[]; /** - * Network to execute the transaction on + * Network to execute the transaction on. */ network?: Network; /** - * Unix timestamp after which the transaction becomes invalid + * Unix timestamp after which the transaction becomes invalid. */ validUntil?: number; @@ -47,27 +47,27 @@ export interface TransactionRequestMessage { address: string; /** - * Amount to transfer in nanos + * Amount to transfer in nanos. */ amount: TokenAmount; /** - * Send mode flags controlling message behavior + * Send mode flags controlling message behavior. */ mode?: SendMode; /** - * Additional currencies to include in the transfer + * Additional currencies to include in the transfer. */ extraCurrency?: ExtraCurrencies; /** - * Initial state for deploying a new contract, encoded in Base64 + * Initial state for deploying a new contract, encoded in Base64. */ stateInit?: Base64String; /** - * Message payload data encoded in Base64 + * Message payload data encoded in Base64. */ payload?: Base64String; } diff --git a/packages/walletkit/src/api/models/transactions/TransactionStatus.ts b/packages/walletkit/src/api/models/transactions/TransactionStatus.ts index 812e04319..4287fcd9d 100644 --- a/packages/walletkit/src/api/models/transactions/TransactionStatus.ts +++ b/packages/walletkit/src/api/models/transactions/TransactionStatus.ts @@ -13,7 +13,7 @@ export type TransactionStatus = | 'failed'; // transaction trace is fully processed onchain and has errors export interface TransactionStatusResponse { - /** Overall status of the transaction trace */ + /** Overall status of the transaction trace. */ status: TransactionStatus; /** * Total messages in the trace diff --git a/packages/walletkit/src/api/models/transactions/TransactionTrace.ts b/packages/walletkit/src/api/models/transactions/TransactionTrace.ts index f9c7d2e15..119976b4d 100644 --- a/packages/walletkit/src/api/models/transactions/TransactionTrace.ts +++ b/packages/walletkit/src/api/models/transactions/TransactionTrace.ts @@ -22,27 +22,27 @@ export interface TransactionTrace { mcBlockSeqno: number; /** - * Root trace node of the execution tree + * Root trace node of the execution tree. */ trace: TransactionTraceNode; /** - * Map of transaction hashes to transaction details + * Map of transaction hashes to transaction details. */ transactions: { [key: Hex]: Transaction }; /** - * List of high-level actions extracted from the trace + * List of high-level actions extracted from the trace. */ actions: TransactionTraceAction[]; /** - * Random seed used for emulation + * Random seed used for emulation. */ randSeed: Hex; /** - * Whether the trace is incomplete due to limits or errors + * Whether the trace is incomplete due to limits or errors. */ isIncomplete: boolean; } @@ -52,17 +52,17 @@ export interface TransactionTrace { */ export interface TransactionTraceNode { /** - * Transaction hash + * Transaction hash. */ txHash?: Hex; /** - * Incoming message hash + * Incoming message hash. */ inMsgHash?: Hex; /** - * Child trace nodes representing spawned messages + * Child trace nodes representing spawned messages. */ children: TransactionTraceNode[]; } @@ -72,25 +72,25 @@ export interface TransactionTraceNode { */ export interface TransactionTraceAction { /** - * Trace identifier + * Trace identifier. */ traceId?: string; /** - * Action identifier + * Action identifier. */ actionId?: string; /** - * Logical time when the action started + * Logical time when the action started. */ startLt?: LogicalTime; /** - * Logical time when the action ended + * Logical time when the action ended. */ endLt?: LogicalTime; /** - * Unix time when the action started + * Unix time when the action started. */ startUtime?: number; /** @@ -99,7 +99,7 @@ export interface TransactionTraceAction { */ endUtime?: number; /** - * Logical time when the trace ended + * Logical time when the trace ended. */ traceEndLt?: LogicalTime; /** @@ -108,33 +108,33 @@ export interface TransactionTraceAction { */ traceEndUtime?: number; /** - * Masterchain block sequence number when the trace ended + * Masterchain block sequence number when the trace ended. */ traceMcSeqnoEnd?: number; /** - * List of transaction hashes involved in this action + * List of transaction hashes involved in this action. */ transactions: Hex[]; /** - * Indicates if the action was successful + * Indicates if the action was successful. */ isSuccess?: boolean; /** - * External hash of the trace + * External hash of the trace. */ traceExternalHash?: Hex; /** - * List of accounts involved in this action + * List of accounts involved in this action. */ accounts: UserFriendlyAddress[]; /** - * Detailed information about the action + * Detailed information about the action. */ details: TransactionTraceActionDetails; } /** - * Details of a transaction trace action + * Details of a transaction trace action. */ export type TransactionTraceActionDetails = | { type: 'jetton_swap'; value: TransactionTraceActionJettonSwapDetails } @@ -147,22 +147,22 @@ export type TransactionTraceActionDetails = */ export interface TransactionTraceActionJettonSwapDetails { /** - * Name of the decentralized exchange + * Name of the decentralized exchange. */ dex: string; /** - * Address of the account initiating the swap + * Address of the account initiating the swap. */ sender?: UserFriendlyAddress; /** - * Transfer details for tokens sent to the DEX + * Transfer details for tokens sent to the DEX. */ dexIncomingTransfer?: TransactionTraceActionJettonTransfer; /** - * Transfer details for tokens received from the DEX + * Transfer details for tokens received from the DEX. */ dexOutgoingTransfer?: TransactionTraceActionJettonTransfer; @@ -253,7 +253,7 @@ export interface TransactionTraceActionTONTransferDetails { valueExtraCurrencies?: ExtraCurrencies; /** - * Optional comment for the transfer + * Optional comment for the transfer. */ comment?: string; diff --git a/packages/walletkit/src/api/models/transactions/TransactionTraceMoneyFlow.ts b/packages/walletkit/src/api/models/transactions/TransactionTraceMoneyFlow.ts index 380546d49..0049dd0bd 100644 --- a/packages/walletkit/src/api/models/transactions/TransactionTraceMoneyFlow.ts +++ b/packages/walletkit/src/api/models/transactions/TransactionTraceMoneyFlow.ts @@ -15,19 +15,19 @@ import type { AssetType } from '../core/AssetType'; */ export interface TransactionTraceMoneyFlow { /** - * Total token amounts output by the transaction + * Total token amounts output by the transaction. */ outputs: TokenAmount; /** - * Total token amounts input to the transaction + * Total token amounts input to the transaction. */ inputs: TokenAmount; /** - * List of all token transfers involved in the transaction + * List of all token transfers involved in the transaction. */ allJettonTransfers: TransactionTraceMoneyFlowItem[]; /** - * List of token transfers involving our address + * List of token transfers involving our address. */ ourTransfers: TransactionTraceMoneyFlowItem[]; /** @@ -41,7 +41,7 @@ export interface TransactionTraceMoneyFlow { */ export interface TransactionTraceMoneyFlowItem { /** - * Type of asset being transferred + * Type of asset being transferred. */ assetType: AssetType; @@ -56,12 +56,12 @@ export interface TransactionTraceMoneyFlowItem { tokenAddress?: UserFriendlyAddress; /** - * Sender address + * Sender address. */ fromAddress?: UserFriendlyAddress; /** - * Recipient address + * Recipient address. */ toAddress?: UserFriendlyAddress; } diff --git a/packages/walletkit/src/api/models/transactions/emulation/TransactionEmulatedPreview.ts b/packages/walletkit/src/api/models/transactions/emulation/TransactionEmulatedPreview.ts index 521f703a9..9ca3fa321 100644 --- a/packages/walletkit/src/api/models/transactions/emulation/TransactionEmulatedPreview.ts +++ b/packages/walletkit/src/api/models/transactions/emulation/TransactionEmulatedPreview.ts @@ -20,17 +20,17 @@ export interface TransactionEmulatedPreview { result: Result; /** - * Error details if the emulation failed + * Error details if the emulation failed. */ error?: ResultError; /** - * Full execution trace if emulation succeeded + * Full execution trace if emulation succeeded. */ trace?: TransactionEmulatedTrace; /** - * Summary of token flows (incoming/outgoing) for the transaction + * Summary of token flows (incoming/outgoing) for the transaction. */ moneyFlow?: TransactionTraceMoneyFlow; } diff --git a/packages/walletkit/src/api/models/transactions/emulation/TransactionEmulatedTrace.ts b/packages/walletkit/src/api/models/transactions/emulation/TransactionEmulatedTrace.ts index 60be4ed64..a774b4602 100644 --- a/packages/walletkit/src/api/models/transactions/emulation/TransactionEmulatedTrace.ts +++ b/packages/walletkit/src/api/models/transactions/emulation/TransactionEmulatedTrace.ts @@ -17,19 +17,19 @@ import type { AddressBook } from '../../core/AddressBook'; */ export interface TransactionEmulatedTrace extends TransactionTrace { /** - * Map of code cell hashes to their Base64-encoded content + * Map of code cell hashes to their Base64-encoded content. */ codeCells: { [key: Hex]: Base64String }; /** - * Map of data cell hashes to their Base64-encoded content + * Map of data cell hashes to their Base64-encoded content. */ dataCells: { [key: Hex]: Base64String }; /** - * Address metadata for accounts involved in the transaction + * Address metadata for accounts involved in the transaction. */ metadata: TransactionAddressMetadata; /** - * Address book mapping addresses to their human-readable names + * Address book mapping addresses to their human-readable names. */ addressBook: AddressBook; } diff --git a/packages/walletkit/src/bridge/core/BridgeConfig.ts b/packages/walletkit/src/bridge/core/BridgeConfig.ts index e06ff57ab..62679a267 100644 --- a/packages/walletkit/src/bridge/core/BridgeConfig.ts +++ b/packages/walletkit/src/bridge/core/BridgeConfig.ts @@ -39,7 +39,7 @@ export interface BridgeConfig { protocolVersion: number; /** - * Id of wallet assosiated with dApp connection in bridge + * ID of wallet assosiated with dApp connection in bridge */ walletId?: WalletId; } diff --git a/packages/walletkit/src/clients/BaseApiClient.ts b/packages/walletkit/src/clients/BaseApiClient.ts index f9966ed92..2525b8852 100644 --- a/packages/walletkit/src/clients/BaseApiClient.ts +++ b/packages/walletkit/src/clients/BaseApiClient.ts @@ -10,11 +10,17 @@ import type { Network } from '../api/models'; import { TonClientError } from './TonClientError'; export interface BaseApiClientConfig { + /** Base URL of the indexer endpoint. Defaults to the provider's mainnet/testnet URL based on `network`. */ endpoint?: string; + /** API key forwarded to the indexer for higher rate limits. */ apiKey?: string; + /** Per-request timeout in milliseconds. Defaults to a provider-specific value. */ timeout?: number; + /** Custom `fetch` implementation. Defaults to the global `fetch`. */ fetchApi?: typeof fetch; + /** {@link Network} the client should target. Determines the default `endpoint` when one isn't supplied. */ network?: Network; + /** When `true`, swallow `sendBoc` calls instead of broadcasting them — useful for local development and tests. */ disableNetworkSend?: boolean; } diff --git a/packages/walletkit/src/clients/tonapi/ApiClientTonApi.ts b/packages/walletkit/src/clients/tonapi/ApiClientTonApi.ts index d930a212c..dc52ec229 100644 --- a/packages/walletkit/src/clients/tonapi/ApiClientTonApi.ts +++ b/packages/walletkit/src/clients/tonapi/ApiClientTonApi.ts @@ -67,6 +67,10 @@ import { mapMasterchainInfo } from './mappers/map-masterchain-info'; * with the default Toncenter client. Some methods are not yet fully implemented. */ export class ApiClientTonApi extends BaseApiClient implements ApiClient { + /** + * @param config - {@link BaseApiClientConfig} TonAPI client config — endpoint URL and API key. Defaults to TonAPI mainnet/testnet URLs based on `config.network`. + * @expand config + */ constructor(config: BaseApiClientConfig = {}) { let defaultEndpoint: string; diff --git a/packages/walletkit/src/clients/toncenter/ApiClientToncenter.ts b/packages/walletkit/src/clients/toncenter/ApiClientToncenter.ts index cf6dd38b9..1b0524374 100644 --- a/packages/walletkit/src/clients/toncenter/ApiClientToncenter.ts +++ b/packages/walletkit/src/clients/toncenter/ApiClientToncenter.ts @@ -65,12 +65,17 @@ import { isHex } from '../../utils'; const log = globalLogger.createChild('ApiClientToncenter'); -export interface ApiClientConfig extends BaseApiClientConfig { +export interface ApiClientToncenterConfig extends BaseApiClientConfig { + /** Override the contract address used to resolve TON DNS records. Defaults to the network's standard root resolver. */ dnsResolver?: string; } export class ApiClientToncenter extends BaseApiClient implements ApiClient { - constructor(config: ApiClientConfig = {}) { + /** + * @param config - {@link ApiClientToncenterConfig} Toncenter client config — endpoint URL, API key and optional DNS resolver override. Defaults to mainnet/testnet Toncenter URLs based on `config.network`. + * @expand config + */ + constructor(config: ApiClientToncenterConfig = {}) { const defaultEndpoint = config.network?.chainId === Network.mainnet().chainId ? 'https://toncenter.com' diff --git a/packages/walletkit/src/clients/toncenter/index.ts b/packages/walletkit/src/clients/toncenter/index.ts index 7133a12ba..d6ef9141d 100644 --- a/packages/walletkit/src/clients/toncenter/index.ts +++ b/packages/walletkit/src/clients/toncenter/index.ts @@ -7,3 +7,5 @@ */ export { ApiClientToncenter } from './ApiClientToncenter'; +export type { ApiClientToncenterConfig } from './ApiClientToncenter'; +export type { BaseApiClientConfig } from '../BaseApiClient'; diff --git a/packages/walletkit/src/core/BridgeManager.ts b/packages/walletkit/src/core/BridgeManager.ts index 4044273f8..ad10eee54 100644 --- a/packages/walletkit/src/core/BridgeManager.ts +++ b/packages/walletkit/src/core/BridgeManager.ts @@ -104,7 +104,7 @@ export class BridgeManager { } /** - * Initialize bridge connection + * Initialize bridge connection. */ async start(): Promise { if (this.bridgeProvider) { @@ -133,7 +133,7 @@ export class BridgeManager { } /** - * Create new session for a dApp connection + * Create new session for a dApp connection. */ async createSession(appSessionId: string): Promise { // const walletSession = new SessionCrypto(); @@ -164,7 +164,7 @@ export class BridgeManager { } /** - * Remove session + * Remove session. */ async removeSession(appSessionId: string): Promise { // const session = this.sessions.get(appSessionId); @@ -181,7 +181,7 @@ export class BridgeManager { } /** - * Send response to dApp + * Send response to dApp. */ async sendResponse( @@ -316,7 +316,7 @@ export class BridgeManager { } /** - * Close bridge connection + * Close bridge connection. */ async close(): Promise { if (this.bridgeProvider) { @@ -338,14 +338,14 @@ export class BridgeManager { } /** - * Get connection status + * Get connection status. */ isConnectedToBridge(): boolean { return this.isConnected; } /** - * Get active session count + * Get active session count. */ // getSessionCount(): number { // return this.sessions.size; @@ -362,7 +362,7 @@ export class BridgeManager { } /** - * Connect to TON Connect bridge + * Connect to TON Connect bridge. */ private async connectToSSEBridge(): Promise { if (!this.config.bridgeUrl) { @@ -452,7 +452,7 @@ export class BridgeManager { } /** - * Restart bridge connection in case of error, so we can receive events again + * Restart bridge connection in case of error, so we can receive events again. */ private async restartConnection(): Promise { await this.close(); @@ -460,7 +460,7 @@ export class BridgeManager { } /** - * Add client to existing bridge connection + * Add client to existing bridge connection. */ private async updateClients(): Promise { log.debug('Updating clients'); @@ -474,7 +474,7 @@ export class BridgeManager { } /** - * Queue incoming bridge events for processing + * Queue incoming bridge events for processing. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any private queueBridgeEvent(event: any): void { @@ -548,7 +548,7 @@ export class BridgeManager { * New events from the bridge added to eventQueue to avoid concurrency * processBridgeEvents takes events from queue one by one and tries to store them durably * if event stored successfully, we will update lastEventId and proceed to the next event - * if we've encountered error, bridge connection we be restarted from last success id, so we should try to process same event again + * if we've encountered error, bridge connection we be restarted from last success id, so we should try to process same event again. */ private async processBridgeEvents(): Promise { // Ensure only one processing instance runs at a time @@ -700,7 +700,7 @@ export class BridgeManager { } /** - * Load last event ID from storage + * Load last event ID from storage. */ private async loadLastEventId(): Promise { try { @@ -720,7 +720,7 @@ export class BridgeManager { } /** - * Save last event ID to storage + * Save last event ID to storage. */ private async saveLastEventId(): Promise { try { diff --git a/packages/walletkit/src/core/EventEmitter.ts b/packages/walletkit/src/core/EventEmitter.ts index d884784bd..49a317857 100644 --- a/packages/walletkit/src/core/EventEmitter.ts +++ b/packages/walletkit/src/core/EventEmitter.ts @@ -15,9 +15,13 @@ const log = globalLogger.createChild('EventEmitter'); export type EventPayload = object; export interface KitEvent { + /** Event name (e.g., `'connector:wallets-updated'`). */ type: string; + /** Event-specific payload — typed via the emitter's event-name → payload map. */ payload: T; + /** Identifier of the component that emitted the event (connector id, manager name, etc.). Useful for filtering listeners. */ source?: string; + /** Wall-clock timestamp in milliseconds when the event was emitted. */ timestamp: number; } @@ -64,7 +68,7 @@ export class EventEmitter { } /** - * Unsubscribe from an event + * Unsubscribe from an event. */ off(eventName: K, listener: EventListener): void { this.listeners[eventName]?.delete(listener); @@ -91,7 +95,7 @@ export class EventEmitter { } /** - * Remove all listeners for a specific event or all events + * Remove all listeners for a specific event or all events. */ removeAllListeners(eventName?: keyof Events): void { if (eventName) { @@ -104,14 +108,14 @@ export class EventEmitter { } /** - * Get the number of listeners for an event + * Get the number of listeners for an event. */ listenerCount(eventName: keyof Events): number { return this.listeners[eventName]?.size || 0; } /** - * Get all event names that have listeners + * Get all event names that have listeners. */ eventNames(): string[] { return Object.keys(this.listeners) as string[]; diff --git a/packages/walletkit/src/core/EventProcessor.ts b/packages/walletkit/src/core/EventProcessor.ts index 648a33f22..b63173e24 100644 --- a/packages/walletkit/src/core/EventProcessor.ts +++ b/packages/walletkit/src/core/EventProcessor.ts @@ -30,7 +30,7 @@ export interface EventProcessorConfig { } /** - * Processes durable events for wallets based on their active sessions and enabled event types + * Processes durable events for wallets based on their active sessions and enabled event types. */ export class StorageEventProcessor implements IEventProcessor { private eventStore: EventStore; @@ -82,7 +82,7 @@ export class StorageEventProcessor implements IEventProcessor { } /** - * Start processing events for a wallet + * Start processing events for a wallet. */ async startProcessing(walletId?: string): Promise { if (this.processorConfig.disableEvents) { @@ -110,7 +110,7 @@ export class StorageEventProcessor implements IEventProcessor { } /** - * Stop processing events for a wallet + * Stop processing events for a wallet. */ async stopProcessing(walletId?: WalletId): Promise { if (this.processorConfig.disableEvents) { @@ -140,7 +140,7 @@ export class StorageEventProcessor implements IEventProcessor { /** * Process next available event from any source (wallet or no-wallet) - * This is the main method used by the global processing loop + * This is the main method used by the global processing loop. */ private async processNextAvailableEvent(): Promise { try { @@ -200,7 +200,7 @@ export class StorageEventProcessor implements IEventProcessor { } /** - * Mark an event as completed after successful processing + * Mark an event as completed after successful processing. */ async completeEvent(eventId: string): Promise { try { @@ -215,7 +215,7 @@ export class StorageEventProcessor implements IEventProcessor { } /** - * Start the recovery process for stale events + * Start the recovery process for stale events. */ startRecoveryLoop(): void { if (this.recoveryTimeoutId) { @@ -263,7 +263,7 @@ export class StorageEventProcessor implements IEventProcessor { } /** - * Stop the recovery process + * Stop the recovery process. */ stopRecoveryLoop(): void { if (this.recoveryTimeoutId) { @@ -283,7 +283,7 @@ export class StorageEventProcessor implements IEventProcessor { /** * Process a single event with retry logic - * Returns true if event was processed successfully, false otherwise + * Returns true if event was processed successfully, false otherwise. */ private async processEvent(event: StoredEvent, walletId: WalletId): Promise { const acquiredEvent = await this.eventStore.acquireLock(event.id, walletId); @@ -364,7 +364,7 @@ export class StorageEventProcessor implements IEventProcessor { } /** - * Main global processing loop for all events + * Main global processing loop for all events. */ private async processEventsLoop(): Promise { while (this.isProcessing) { @@ -391,7 +391,7 @@ export class StorageEventProcessor implements IEventProcessor { } /** - * Trigger the global processing loop + * Trigger the global processing loop. */ private triggerProcessing(): void { if (this.isProcessing && this.wakeUpResolver) { @@ -401,7 +401,7 @@ export class StorageEventProcessor implements IEventProcessor { } /** - * Wait for either a wake-up signal or timeout + * Wait for either a wake-up signal or timeout. */ private async waitForWakeUpOrTimeout(timeoutMs: number): Promise { return new Promise((resolve) => { @@ -424,7 +424,7 @@ export class StorageEventProcessor implements IEventProcessor { } /** - * Get enabled event types based on registered handlers in EventRouter + * Get enabled event types based on registered handlers in EventRouter. */ private getEnabledEventTypes(): EventType[] { return this.eventRouter.getEnabledEventTypes(); diff --git a/packages/walletkit/src/core/EventRouter.ts b/packages/walletkit/src/core/EventRouter.ts index 06ab8b668..251738e68 100644 --- a/packages/walletkit/src/core/EventRouter.ts +++ b/packages/walletkit/src/core/EventRouter.ts @@ -58,7 +58,7 @@ export class EventRouter { } /** - * Route incoming bridge event to appropriate handler + * Route incoming bridge event to appropriate handler. */ async routeEvent(event: RawBridgeEvent): Promise { // Validate event structure @@ -93,7 +93,7 @@ export class EventRouter { } /** - * Register event callbacks + * Register event callbacks. */ onConnectRequest(callback: EventCallback): void { this.connectRequestCallback = callback; @@ -116,7 +116,7 @@ export class EventRouter { } /** - * Remove specific callback + * Remove specific callback. */ removeConnectRequestCallback(): void { this.connectRequestCallback = undefined; @@ -139,7 +139,7 @@ export class EventRouter { } /** - * Clear all callbacks + * Clear all callbacks. */ clearCallbacks(): void { this.connectRequestCallback = undefined; @@ -150,7 +150,7 @@ export class EventRouter { } /** - * Setup event handlers + * Setup event handlers. */ private setupHandlers(): void { this.handlers = [ @@ -174,42 +174,42 @@ export class EventRouter { } /** - * Notify connect request callbacks + * Notify connect request callbacks. */ private async notifyConnectRequestCallbacks(event: ConnectionRequestEvent): Promise { return await this.connectRequestCallback?.(event); } /** - * Notify transaction request callbacks + * Notify transaction request callbacks. */ private async notifyTransactionRequestCallbacks(event: SendTransactionRequestEvent): Promise { return await this.transactionRequestCallback?.(event); } /** - * Notify sign data request callbacks + * Notify sign data request callbacks. */ private async notifySignDataRequestCallbacks(event: SignDataRequestEvent): Promise { return await this.signDataRequestCallback?.(event); } /** - * Notify disconnect callbacks + * Notify disconnect callbacks. */ private async notifyDisconnectCallbacks(event: DisconnectionEvent): Promise { return await this.disconnectCallback?.(event); } /** - * Notify error callbacks + * Notify error callbacks. */ private async notifyErrorCallback(event: RequestErrorEvent): Promise { return await this.errorCallback?.(event); } /** - * Get enabled event types based on registered callbacks + * Get enabled event types based on registered callbacks. */ getEnabledEventTypes(): EventType[] { const enabledTypes: EventType[] = []; diff --git a/packages/walletkit/src/core/EventStore.ts b/packages/walletkit/src/core/EventStore.ts index c66b4c6fd..c086e4249 100644 --- a/packages/walletkit/src/core/EventStore.ts +++ b/packages/walletkit/src/core/EventStore.ts @@ -23,7 +23,7 @@ const log = globalLogger.createChild('EventStore'); const MAX_EVENT_SIZE_BYTES = 100 * 1024; // 100kb /** - * Concrete implementation of EventStore using Storage + * Concrete implementation of EventStore using Storage. */ export class StorageEventStore implements EventStore { private storage: Storage; @@ -35,7 +35,7 @@ export class StorageEventStore implements EventStore { } /** - * Store a new event from the bridge + * Store a new event from the bridge. */ async storeEvent(_rawEvent: RawBridgeEvent): Promise { const rawEvent = { ..._rawEvent, wallet: undefined }; @@ -81,7 +81,7 @@ export class StorageEventStore implements EventStore { } /** - * Get events for a wallet that are ready for processing + * Get events for a wallet that are ready for processing. */ async getEventsForWallet(sessionIds: string[], eventTypes: EventType[]): Promise { const events = await this.getAllEvents(); @@ -118,7 +118,7 @@ export class StorageEventStore implements EventStore { } /** - * Attempt to acquire exclusive lock on an event for processing + * Attempt to acquire exclusive lock on an event for processing. */ async acquireLock(eventId: string, walletId: string): Promise { return this.withLock('storage', async () => { @@ -156,7 +156,7 @@ export class StorageEventStore implements EventStore { } /** - * Increment retry count and update error message for an event + * Increment retry count and update error message for an event. */ async releaseLock(eventId: string, error?: string): Promise { return this.withLock('storage', async () => { @@ -197,7 +197,7 @@ export class StorageEventStore implements EventStore { } /** - * Update event status and timestamps with optimistic locking + * Update event status and timestamps with optimistic locking. */ async updateEventStatus(eventId: string, status: EventStatus, oldStatus: EventStatus): Promise { return this.withLock('storage', async () => { @@ -234,7 +234,7 @@ export class StorageEventStore implements EventStore { } /** - * Get event by ID + * Get event by ID. */ async getEvent(eventId: string): Promise { try { @@ -247,7 +247,7 @@ export class StorageEventStore implements EventStore { } /** - * Recover stale events that have been processing too long + * Recover stale events that have been processing too long. */ async recoverStaleEvents(processingTimeoutMs: number): Promise { const events = await this.getAllEvents(); @@ -287,7 +287,7 @@ export class StorageEventStore implements EventStore { } /** - * Clean up old completed events + * Clean up old completed events. */ async cleanupOldEvents(retentionMs: number): Promise { const events = await this.getAllEvents(); diff --git a/packages/walletkit/src/core/Initializer.ts b/packages/walletkit/src/core/Initializer.ts index cc112534e..8e510432e 100644 --- a/packages/walletkit/src/core/Initializer.ts +++ b/packages/walletkit/src/core/Initializer.ts @@ -32,7 +32,7 @@ import type { Wallet, WalletAdapter } from '../api/interfaces'; const log = globalLogger.createChild('Initializer'); /** - * Initialization result + * Initialization result. */ export interface InitializationResult { walletManager: WalletManager; @@ -45,7 +45,7 @@ export interface InitializationResult { } /** - * Handles initialization of all TonWalletKit components + * Handles initialization of all TonWalletKit components. */ export class Initializer { private config: TonWalletKitOptions; @@ -60,7 +60,7 @@ export class Initializer { } /** - * Initialize all components + * Initialize all components. */ async initialize(options: TonWalletKitOptions, networkManager: NetworkManager): Promise { try { @@ -96,7 +96,7 @@ export class Initializer { } /** - * Initialize storage adapter and wrap it in Storage + * Initialize storage adapter and wrap it in Storage. */ private initializeStorage(options: TonWalletKitOptions): Storage { let adapter: StorageAdapter; @@ -127,7 +127,7 @@ export class Initializer { } /** - * Initialize core managers + * Initialize core managers. */ private async initializeManagers( options: TonWalletKitOptions, @@ -205,7 +205,7 @@ export class Initializer { } /** - * Initialize processors + * Initialize processors. */ private initializeProcessors( sessionManager: TONConnectSessionManager, @@ -228,7 +228,7 @@ export class Initializer { } /** - * Cleanup resources during shutdown + * Cleanup resources during shutdown. */ async cleanup(components: Partial): Promise { try { @@ -258,7 +258,7 @@ export class Initializer { /** * Wrap wallet adapter with extension interfaces (Ton, Jetton, NFT) * Uses proxy API to make wallet extension modular - * The wallet adapter already contains its own ApiClient for its network + * The wallet adapter already contains its own ApiClient for its network. */ export async function wrapWalletInterface(wallet: WalletAdapter): Promise { const ourClassesToExtend = [WalletTonClass, WalletJettonClass, WalletNftClass]; diff --git a/packages/walletkit/src/core/JettonsManager.ts b/packages/walletkit/src/core/JettonsManager.ts index 5d2aa3e50..eec65ded2 100644 --- a/packages/walletkit/src/core/JettonsManager.ts +++ b/packages/walletkit/src/core/JettonsManager.ts @@ -24,7 +24,7 @@ import { asMaybeAddressFriendly } from '../utils'; const log = globalLogger.createChild('JettonsManager'); /** - * Creates a cache key that includes the network ID + * Creates a cache key that includes the network ID. */ function createCacheKey(network: Network, address: string): string { return `${network.chainId}:${address}`; @@ -32,7 +32,7 @@ function createCacheKey(network: Network, address: string): string { /** * JettonsManager - manages jetton information with LRU caching and TonCenter API integration - * Jettons are cached per network to support multi-network scenarios + * Jettons are cached per network to support multi-network scenarios. */ export class JettonsManager implements JettonsAPI { private cache: LRUCache; @@ -70,7 +70,7 @@ export class JettonsManager implements JettonsAPI { } /** - * Add TON native token to cache for a specific network + * Add TON native token to cache for a specific network. */ private addTonToCache(network: Network): void { const cacheKey = createCacheKey(network, 'TON'); @@ -211,7 +211,7 @@ export class JettonsManager implements JettonsAPI { } /** - * Add jetton info to cache from emulation data for a specific network + * Add jetton info to cache from emulation data for a specific network. */ addJettonFromEmulation(network: Network, jettonAddress: string, emulationInfo: EmulationTokenInfoMasters): void { try { @@ -243,7 +243,7 @@ export class JettonsManager implements JettonsAPI { } /** - * Add multiple jettons from emulation metadata for a specific network + * Add multiple jettons from emulation metadata for a specific network. */ addJettonsFromEmulationMetadata( network: Network, @@ -287,7 +287,7 @@ export class JettonsManager implements JettonsAPI { } /** - * Normalize jetton address for consistent caching + * Normalize jetton address for consistent caching. */ private normalizedCacheKey(network: Network, address: string): string { if (address === 'TON') { @@ -297,7 +297,7 @@ export class JettonsManager implements JettonsAPI { } /** - * Get cache statistics + * Get cache statistics. */ getCacheStats(): { size: number; capacity: number } { return { @@ -307,7 +307,7 @@ export class JettonsManager implements JettonsAPI { } /** - * Validate jetton address format + * Validate jetton address format. */ validateJettonAddress(address: string): boolean { try { @@ -324,7 +324,7 @@ export class JettonsManager implements JettonsAPI { } /** - * Clear the jetton cache for all networks or a specific network + * Clear the jetton cache for all networks or a specific network. */ clearCache(network?: Network): void { if (network) { diff --git a/packages/walletkit/src/core/Logger.ts b/packages/walletkit/src/core/Logger.ts index dbecae76f..71b666e99 100644 --- a/packages/walletkit/src/core/Logger.ts +++ b/packages/walletkit/src/core/Logger.ts @@ -36,7 +36,7 @@ */ /** - * Log levels enum for controlling logger verbosity + * Log levels enum for controlling logger verbosity. */ export enum LogLevel { DEBUG = 0, @@ -47,7 +47,7 @@ export enum LogLevel { } /** - * Logger configuration interface + * Logger configuration interface. */ export interface LoggerConfig { level: LogLevel; @@ -58,7 +58,7 @@ export interface LoggerConfig { } /** - * Context object for structured logging + * Context object for structured logging. */ export interface LogContext { // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -84,7 +84,7 @@ function getDefaultLogLevel(): LogLevel { /** * Logger class for TonWalletKit - * Provides structured logging with configurable levels and context support + * Provides structured logging with configurable levels and context support. */ export class Logger { private config: LoggerConfig; @@ -113,14 +113,14 @@ export class Logger { } /** - * Update logger configuration + * Update logger configuration. */ configure(config: Partial): void { this.config = { ...this.config, ...config }; } /** - * Create a child logger with a prefix that inherits from this logger + * Create a child logger with a prefix that inherits from this logger. */ createChild(prefix: string, config?: Partial): Logger { return new Logger({ @@ -131,7 +131,7 @@ export class Logger { } /** - * Build hierarchical prefix by combining parent prefix with current prefix + * Build hierarchical prefix by combining parent prefix with current prefix. */ private buildHierarchicalPrefix(currentPrefix?: string): string { if (!this.parent || !currentPrefix) { @@ -147,21 +147,21 @@ export class Logger { } /** - * Get the full hierarchical prefix for this logger + * Get the full hierarchical prefix for this logger. */ getPrefix(): string { return this.config.prefix || ''; } /** - * Get the parent logger if it exists + * Get the parent logger if it exists. */ getParent(): Logger | undefined { return this.parent; } /** - * Log debug messages + * Log debug messages. */ debug(message: string, context?: LogContext): void { if (this.config.level <= LogLevel.DEBUG) { @@ -170,7 +170,7 @@ export class Logger { } /** - * Log info messages + * Log info messages. */ info(message: string, context?: LogContext): void { if (this.config.level <= LogLevel.INFO) { @@ -179,7 +179,7 @@ export class Logger { } /** - * Log warning messages + * Log warning messages. */ warn(message: string, context?: LogContext): void { if (this.config.level <= LogLevel.WARN) { @@ -188,7 +188,7 @@ export class Logger { } /** - * Log error messages + * Log error messages. */ error(message: string, context?: LogContext): void { if (this.config.level <= LogLevel.ERROR) { @@ -197,7 +197,7 @@ export class Logger { } /** - * Internal logging method + * Internal logging method. */ private log(level: string, message: string, context?: LogContext): void { const timestamp = this.config.enableTimestamp ? new Date().toISOString() : ''; @@ -249,7 +249,7 @@ export class Logger { } /** - * Default logger instance + * Default logger instance. */ export const globalLogger = new Logger({ level: getDefaultLogLevel(), @@ -257,7 +257,7 @@ export const globalLogger = new Logger({ }); /** - * Create a logger with custom configuration + * Create a logger with custom configuration. */ export function createLogger(config?: Partial): Logger { return new Logger(config); diff --git a/packages/walletkit/src/core/NetworkManager.ts b/packages/walletkit/src/core/NetworkManager.ts index 021739425..fe485838f 100644 --- a/packages/walletkit/src/core/NetworkManager.ts +++ b/packages/walletkit/src/core/NetworkManager.ts @@ -32,6 +32,7 @@ export interface NetworkManager { export class KitNetworkManager implements NetworkManager { private clients: Map = new Map(); + /** @param options - {@link TonWalletKitOptions} Configuration carrying the `networks` map keyed by chain ID. At least one network must be configured. */ constructor(options: TonWalletKitOptions) { this.initializeClients(options); @@ -46,7 +47,7 @@ export class KitNetworkManager implements NetworkManager { } /** - * Initialize API clients from configuration + * Initialize API clients from configuration. */ private initializeClients(options: TonWalletKitOptions): void { const networks = options.networks; @@ -69,7 +70,7 @@ export class KitNetworkManager implements NetworkManager { } /** - * Create an API client for a specific network + * Create an API client for a specific network. */ private createClient( network: Network, @@ -103,7 +104,7 @@ export class KitNetworkManager implements NetworkManager { } /** - * Type guard to check if value is a full ApiClient instance + * Type guard to check if value is a full ApiClient instance. */ private isApiClient(value: ApiClientConfig | ApiClient | undefined): value is ApiClient { return ( @@ -141,21 +142,21 @@ export class KitNetworkManager implements NetworkManager { } /** - * Check if a network is configured + * Check if a network is configured. */ hasNetwork(network: Network): boolean { return this.clients.has(network.chainId); } /** - * Get all configured networks + * Get all configured networks. */ getConfiguredNetworks(): Network[] { return Array.from(this.clients.keys()).map((chainId) => Network.custom(chainId)); } /** - * Add or update a network client dynamically + * Add or update a network client dynamically. */ setClient(network: Network, client: ApiClient): void { this.clients.set(network.chainId, client); diff --git a/packages/walletkit/src/core/RequestProcessor.ts b/packages/walletkit/src/core/RequestProcessor.ts index 3242061c1..8169585d0 100644 --- a/packages/walletkit/src/core/RequestProcessor.ts +++ b/packages/walletkit/src/core/RequestProcessor.ts @@ -56,7 +56,7 @@ import type { Analytics, AnalyticsManager } from '../analytics'; const log = globalLogger.createChild('RequestProcessor'); /** - * Handles approval and rejection of various request types + * Handles approval and rejection of various request types. */ export class RequestProcessor { private analytics?: Analytics; @@ -72,7 +72,7 @@ export class RequestProcessor { } /** - * Helper to get wallet from event, supporting both walletId and walletAddress + * Helper to get wallet from event, supporting both walletId and walletAddress. */ private getWalletFromEvent(event: { walletId?: string }): Wallet | undefined { if (event.walletId) { @@ -82,7 +82,7 @@ export class RequestProcessor { } /** - * Helper to get wallet address from event + * Helper to get wallet address from event. */ private getWalletAddressFromEvent(event: { walletId?: string; walletAddress?: string }): string | undefined { if (event.walletAddress) { @@ -95,7 +95,7 @@ export class RequestProcessor { } /** - * Process connect request approval + * Process connect request approval. */ async approveConnectRequest(event: ConnectionRequestEvent, response?: ConnectionApprovalResponse): Promise { try { @@ -182,7 +182,7 @@ export class RequestProcessor { } /** - * Process connect request rejection + * Process connect request rejection. */ async rejectConnectRequest( event: ConnectionRequestEvent, @@ -251,7 +251,7 @@ export class RequestProcessor { } /** - * Process transaction request approval + * Process transaction request approval. */ async approveTransactionRequest( event: SendTransactionRequestEvent, @@ -299,7 +299,7 @@ export class RequestProcessor { } /** - * Send transaction analytics events + * Send transaction analytics events. */ private sendTransactionAnalytics(event: SendTransactionRequestEvent, signedBoc: string): void { if (!this.analytics) return; @@ -315,7 +315,7 @@ export class RequestProcessor { } /** - * Process transaction request rejection + * Process transaction request rejection. */ async rejectTransactionRequest( event: SendTransactionRequestEvent, @@ -361,7 +361,7 @@ export class RequestProcessor { } /** - * Process sign data request approval + * Process sign data request approval. */ async approveSignDataRequest( event: SignDataRequestEvent, @@ -517,7 +517,7 @@ export class RequestProcessor { } /** - * Process sign data request rejection + * Process sign data request rejection. */ async rejectSignDataRequest(event: SignDataRequestEvent, reason?: string): Promise { try { @@ -559,7 +559,7 @@ export class RequestProcessor { } /** - * Create connect approval response + * Create connect approval response. */ private async createConnectApprovalResponse( event: ConnectionRequestEvent, @@ -627,7 +627,7 @@ export class RequestProcessor { } /** - * Sign transaction and return BOC + * Sign transaction and return BOC. */ private async signTransaction(event: SendTransactionRequestEvent): Promise { const walletId = event.walletId; @@ -669,7 +669,7 @@ export class RequestProcessor { /** * Get API client for a wallet's network - * Uses the wallet's network to get the appropriate client from NetworkManager + * Uses the wallet's network to get the appropriate client from NetworkManager. */ private getClientForWallet(walletId: string | undefined) { if (!walletId) { @@ -686,7 +686,7 @@ export class RequestProcessor { } /** - * Internal helper to sign transaction + * Internal helper to sign transaction. */ export async function signTransactionInternal(wallet: Wallet, request: TransactionRequest): Promise { const signedBoc = await wallet.getSignedSendTransaction(request, { diff --git a/packages/walletkit/src/core/TONConnectStoredSessionManager.ts b/packages/walletkit/src/core/TONConnectStoredSessionManager.ts index a144e1ec6..df76a9f24 100644 --- a/packages/walletkit/src/core/TONConnectStoredSessionManager.ts +++ b/packages/walletkit/src/core/TONConnectStoredSessionManager.ts @@ -34,7 +34,7 @@ export class TONConnectStoredSessionManager implements TONConnectSessionManager } /** - * Initialize manager and load persisted sessions + * Initialize manager and load persisted sessions. */ async initialize(): Promise { await this.loadSessions(); @@ -93,7 +93,7 @@ export class TONConnectStoredSessionManager implements TONConnectSessionManager } /** - * Get session by ID + * Get session by ID. */ async getSession(sessionId: string): Promise { return this.sessions.get(sessionId); @@ -139,7 +139,7 @@ export class TONConnectStoredSessionManager implements TONConnectSessionManager } /** - * Remove session by ID + * Remove session by ID. */ async removeSession(sessionId: string): Promise { const removed = this.sessions.delete(sessionId); @@ -165,7 +165,7 @@ export class TONConnectStoredSessionManager implements TONConnectSessionManager } /** - * Clear all sessions + * Clear all sessions. */ async clearSessions(): Promise { this.sessions.clear(); @@ -173,14 +173,14 @@ export class TONConnectStoredSessionManager implements TONConnectSessionManager } /** - * Get session count + * Get session count. */ getSessionCount(): number { return this.sessions.size; } /** - * Check if session exists + * Check if session exists. */ hasSession(sessionId: string): boolean { return this.sessions.has(sessionId); @@ -214,7 +214,7 @@ export class TONConnectStoredSessionManager implements TONConnectSessionManager } /** - * Load sessions from storage + * Load sessions from storage. */ private async loadSessions(): Promise { try { @@ -241,7 +241,7 @@ export class TONConnectStoredSessionManager implements TONConnectSessionManager } /** - * Persist session metadata to storage + * Persist session metadata to storage. */ private async persistSessions(): Promise { try { diff --git a/packages/walletkit/src/core/TonWalletKit.ts b/packages/walletkit/src/core/TonWalletKit.ts index dad6a2fa4..c9121836d 100644 --- a/packages/walletkit/src/core/TonWalletKit.ts +++ b/packages/walletkit/src/core/TonWalletKit.ts @@ -81,7 +81,7 @@ const log = globalLogger.createChild('TonWalletKit'); * - EventRouter: event parsing & routing * - RequestProcessor: request approval/rejection * - ResponseHandler: response formatting & sending - * - Initializer: component setup & teardown + * - Initializer: component setup & teardown. */ export class TonWalletKit implements ITonWalletKit { // Component references @@ -209,7 +209,6 @@ export class TonWalletKit implements ITonWalletKit { return { networkManager: this.networkManager, eventEmitter: this.eventEmitter, - ssr: false, }; } @@ -234,7 +233,7 @@ export class TonWalletKit implements ITonWalletKit { // === Initialization === /** - * Initialize all components + * Initialize all components. */ private async initialize(): Promise { if (this.isInitialized) return; @@ -259,7 +258,7 @@ export class TonWalletKit implements ITonWalletKit { } /** - * Assign initialized components + * Assign initialized components. */ private assignComponents(components: InitializationResult): void { this.walletManager = components.walletManager; @@ -271,7 +270,7 @@ export class TonWalletKit implements ITonWalletKit { } /** - * Setup event routing from bridge to handlers + * Setup event routing from bridge to handlers. */ private async setupEventRouting(): Promise { // The event routing logic will use the existing EventRouter @@ -282,7 +281,7 @@ export class TonWalletKit implements ITonWalletKit { } /** - * Start event processing for all existing wallets + * Start event processing for all existing wallets. */ private async startProcessingForExistingWallets(): Promise { const wallets = this.walletManager.getWallets(); @@ -301,7 +300,7 @@ export class TonWalletKit implements ITonWalletKit { } /** - * Ensure initialization is complete + * Ensure initialization is complete. */ async ensureInitialized(): Promise { if (this.initializationPromise) { @@ -310,7 +309,7 @@ export class TonWalletKit implements ITonWalletKit { } /** - * Get all configured networks + * Get all configured networks. */ getConfiguredNetworks(): Network[] { return this.networkManager.getConfiguredNetworks(); @@ -543,7 +542,7 @@ export class TonWalletKit implements ITonWalletKit { // === URL Parsing API === /** - * Allow to convert url to ConnectionRequestEvent to use inline way + * Allow to convert url to ConnectionRequestEvent to use inline way. */ async connectionEventFromUrl(url: string): Promise { await this.ensureInitialized(); @@ -562,7 +561,7 @@ export class TonWalletKit implements ITonWalletKit { /** * Handle pasted TON Connect URL/link - * Parses the URL and creates a connect request event + * Parses the URL and creates a connect request event. */ async handleTonConnectUrl(url: string): Promise { await this.ensureInitialized(); @@ -597,7 +596,7 @@ export class TonWalletKit implements ITonWalletKit { } /** - * Parse and validate TON Connect URL into a RawBridgeEventConnect + * Parse and validate TON Connect URL into a RawBridgeEventConnect. */ private parseBridgeConnectEventFromUrl(url: string): RawBridgeEventConnect { const parsedUrl = this.parseTonConnectUrl(url); @@ -621,7 +620,7 @@ export class TonWalletKit implements ITonWalletKit { } /** - * Parse TON Connect URL to extract connection parameters + * Parse TON Connect URL to extract connection parameters. */ private parseTonConnectUrl(url: string): { version: string; @@ -663,7 +662,7 @@ export class TonWalletKit implements ITonWalletKit { } /** - * Create bridge event from parsed URL parameters + * Create bridge event from parsed URL parameters. */ private createConnectEventFromUrl(params: { version: string; @@ -753,7 +752,7 @@ export class TonWalletKit implements ITonWalletKit { /** * Get the NetworkManager instance - * Provides access to all configured network clients + * Provides access to all configured network clients. */ getNetworkManager(): NetworkManager { return this.networkManager; @@ -762,21 +761,21 @@ export class TonWalletKit implements ITonWalletKit { // === Lifecycle Management === /** - * Check if kit is ready for use + * Check if kit is ready for use. */ isReady(): boolean { return this.isInitialized; } /** - * Wait for initialization to complete + * Wait for initialization to complete. */ async waitForReady(): Promise { await this.ensureInitialized(); } /** - * Get initialization status + * Get initialization status. */ getStatus(): { initialized: boolean; ready: boolean } { return { @@ -786,7 +785,7 @@ export class TonWalletKit implements ITonWalletKit { } /** - * Clean shutdown + * Clean shutdown. */ async close(): Promise { if (this.initializer) { @@ -806,35 +805,35 @@ export class TonWalletKit implements ITonWalletKit { // === Jettons API === /** - * Jettons API access + * Jettons API access. */ get jettons(): JettonsAPI { return this.jettonsManager; } /** - * Get jettons manager for internal use + * Get jettons manager for internal use. */ getJettonsManager(): JettonsManager { return this.jettonsManager; } /** - * Swap API access + * Swap API access. */ get swap(): SwapManager { return this.swapManager; } /** - * Streaming API access + * Streaming API access. */ get streaming(): StreamingAPI { return this.streamingManager; } /** - * Staking API access + * Staking API access. */ get staking(): StakingManager { return this.stakingManager; @@ -842,7 +841,7 @@ export class TonWalletKit implements ITonWalletKit { /** * Get the event emitter for this kit instance - * Allows external components to listen to and emit events + * Allows external components to listen to and emit events. */ getEventEmitter(): WalletKitEventEmitter { return this.eventEmitter; diff --git a/packages/walletkit/src/core/WalletManager.ts b/packages/walletkit/src/core/WalletManager.ts index 0dc4f6df5..6ae4faa40 100644 --- a/packages/walletkit/src/core/WalletManager.ts +++ b/packages/walletkit/src/core/WalletManager.ts @@ -26,14 +26,14 @@ export class WalletManager { } /** - * Initialize manager and load persisted wallets + * Initialize manager and load persisted wallets. */ async initialize(): Promise { // await this.loadWallets(); } /** - * Get all wallets as array + * Get all wallets as array. */ getWallets(): Wallet[] { return Array.from(this.wallets.values()); @@ -47,7 +47,7 @@ export class WalletManager { } /** - * Add a wallet with validation + * Add a wallet with validation. */ async addWallet(wallet: Wallet): Promise { const validation = validateWallet(wallet); @@ -65,7 +65,7 @@ export class WalletManager { } /** - * Remove wallet by wallet ID or wallet adapter + * Remove wallet by wallet ID or wallet adapter. */ async removeWallet(walletIdOrAdapter: WalletId | WalletAdapter): Promise { let walletId: WalletId; @@ -80,7 +80,7 @@ export class WalletManager { } /** - * Update existing wallet + * Update existing wallet. */ async updateWallet(wallet: Wallet): Promise { const walletId = wallet.getWalletId(); @@ -97,28 +97,28 @@ export class WalletManager { } /** - * Clear all wallets + * Clear all wallets. */ async clearWallets(): Promise { this.wallets.clear(); } /** - * Get wallet count + * Get wallet count. */ getWalletCount(): number { return this.wallets.size; } /** - * Check if wallet exists by wallet ID + * Check if wallet exists by wallet ID. */ hasWallet(walletId: WalletId): boolean { return this.wallets.has(walletId); } /** - * Get wallet ID for a wallet adapter + * Get wallet ID for a wallet adapter. */ getWalletId(wallet: WalletAdapter): WalletId { return wallet.getWalletId(); diff --git a/packages/walletkit/src/defi/crypto-onramp/CryptoOnrampProvider.ts b/packages/walletkit/src/defi/crypto-onramp/CryptoOnrampProvider.ts index 4ea097e80..d05d67c45 100644 --- a/packages/walletkit/src/defi/crypto-onramp/CryptoOnrampProvider.ts +++ b/packages/walletkit/src/defi/crypto-onramp/CryptoOnrampProvider.ts @@ -19,23 +19,9 @@ import type { import type { CryptoOnrampProviderInterface } from '../../api/interfaces'; /** - * Abstract base class for crypto onramp providers + * Abstract base class for crypto onramp providers. * - * Provides a common interface for implementing crypto-to-TON onramp functionality - * across different gateways. - * - * @example - * ```typescript - * class MyCryptoOnrampProvider extends CryptoOnrampProvider { - * async getQuote(params: CryptoOnrampQuoteParams): Promise { - * // Implementation - * } - * - * async createDeposit(params: CryptoOnrampDepositParams): Promise { - * // Implementation - * } - * } - * ``` + * Provides a common interface for implementing crypto-to-TON onramp functionality across different gateways. Apps don't typically subclass it directly — use the bundled factories ({@link createLayerswapProvider}, {@link createSwapsXyzProvider}) or build a custom provider through `createProvider`. */ export abstract class CryptoOnrampProvider< TQuoteOptions = undefined, diff --git a/packages/walletkit/src/defi/crypto-onramp/README.md b/packages/walletkit/src/defi/crypto-onramp/README.md index b280ce500..868d7f53b 100644 --- a/packages/walletkit/src/defi/crypto-onramp/README.md +++ b/packages/walletkit/src/defi/crypto-onramp/README.md @@ -1,7 +1,7 @@ # Crypto Onramp Manager @@ -36,7 +36,7 @@ All providers accept the same base parameters for `getQuote`: interface CryptoOnrampQuoteParams { amount: string; // Amount in base units (source or target, see isSourceAmount) sourceCurrencyAddress: string; // Source token contract address (or native zero address) - sourceChain: string; // Source chain identifier in CAIP-2 format (e.g. 'eip155:1', 'eip155:42161') + sourceNetwork: string; // Source chain identifier targetCurrencyAddress: string; // Target TON token address recipientAddress: string; // TON address that will receive the target crypto refundAddress?: string; // Refund address on the source chain (required by some providers) @@ -50,7 +50,7 @@ interface CryptoOnrampQuoteParams { ```typescript const quote = await kit.cryptoOnramp.getQuote({ sourceCurrencyAddress: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9', // USDT on Arbitrum - sourceChain: 'eip155:42161', // Arbitrum One in CAIP-2 format + sourceNetwork: '42161', // Arbitrum One chain ID targetCurrencyAddress: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs', // USDT on TON amount: '1000000', // 1 USDT (6 decimals) recipientAddress: 'UQ...', // TON address to receive the bridged tokens @@ -120,7 +120,7 @@ export class MyCryptoOnrampProvider extends CryptoOnrampProvider // Fetch quote from your bridge API... return { sourceCurrencyAddress, - sourceChain: params.sourceChain, + sourceNetwork: params.sourceNetwork, targetCurrencyAddress, sourceAmount: '...', targetAmount: '...', @@ -132,7 +132,7 @@ export class MyCryptoOnrampProvider extends CryptoOnrampProvider async createDeposit(params: CryptoOnrampDepositParams): Promise { // params.quote.recipientAddress holds the TON recipient set at quote time - return { depositId: '...', address: '0x...', amount: '...', sourceCurrencyAddress: '...', sourceChain: '...', providerId: this.providerId }; + return { depositId: '...', address: '0x...', amount: '...', sourceCurrencyAddress: '...', sourceNetwork: '...', providerId: this.providerId }; } async getStatus(params: CryptoOnrampStatusParams): Promise { @@ -154,7 +154,7 @@ export class MyCryptoOnrampProvider extends CryptoOnrampProvider Get a quote for a crypto-to-TON bridge operation. **Parameters:** -- `params: CryptoOnrampQuoteParams` – `sourceCurrencyAddress`, `sourceChain`, `targetCurrencyAddress`, `amount`, `recipientAddress`, `isSourceAmount?`, `refundAddress?`, `providerOptions?` +- `params: CryptoOnrampQuoteParams` – `sourceCurrencyAddress`, `sourceNetwork`, `targetCurrencyAddress`, `amount`, `recipientAddress`, `isSourceAmount?`, `refundAddress?`, `providerOptions?` - `providerId?: string` – Provider to use (uses default if omitted) **Returns:** `Promise` diff --git a/packages/walletkit/src/defi/crypto-onramp/errors.ts b/packages/walletkit/src/defi/crypto-onramp/errors.ts index 1a3f9ec58..6630c148e 100644 --- a/packages/walletkit/src/defi/crypto-onramp/errors.ts +++ b/packages/walletkit/src/defi/crypto-onramp/errors.ts @@ -9,18 +9,30 @@ import { DefiError } from '../errors'; export enum CryptoOnrampErrorCode { + /** Provider's upstream API rejected the call (unexpected response, auth failure, internal error). */ ProviderError = 'PROVIDER_ERROR', + /** Provider could not produce a quote for the supplied parameters. */ QuoteFailed = 'QUOTE_FAILED', + /** Provider could not create a deposit for the previously obtained quote. */ DepositFailed = 'DEPOSIT_FAILED', + /** Provider requires a refund address that the caller did not supply. */ RefundAddressRequired = 'REFUND_ADDRESS_REQUIRED', + /** Supplied refund address is not valid for the source chain. */ InvalidRefundAddress = 'INVALID_REFUND_ADDRESS', + /** Provider does not support specifying the amount on the target side of the swap. */ ReversedAmountNotSupported = 'REVERSED_AMOUNT_NOT_SUPPORTED', + /** Caller passed parameters that fail provider-level validation. */ InvalidParams = 'INVALID_PARAMS', } export class CryptoOnrampError extends DefiError { public readonly code: CryptoOnrampErrorCode; + /** + * @param message - Human-readable description, forwarded to `Error`. + * @param code - {@link CryptoOnrampErrorCode} Stable error code for branching logic. + * @param details - Optional provider-specific context for diagnostics. + */ constructor(message: string, code: CryptoOnrampErrorCode, details?: unknown) { super(message, code, details); this.name = 'CryptoOnrampError'; diff --git a/packages/walletkit/src/defi/crypto-onramp/layerswap/LayerswapCryptoOnrampProvider.ts b/packages/walletkit/src/defi/crypto-onramp/layerswap/LayerswapCryptoOnrampProvider.ts index a9e31aa19..42bf1cc44 100644 --- a/packages/walletkit/src/defi/crypto-onramp/layerswap/LayerswapCryptoOnrampProvider.ts +++ b/packages/walletkit/src/defi/crypto-onramp/layerswap/LayerswapCryptoOnrampProvider.ts @@ -44,7 +44,7 @@ export interface LayerswapProviderConfig { apiKey?: string; /** - * Override the base API URL. Defaults to https://api.layerswap.io/api/v2 + * Override the base API URL. Defaults to https://api.layerswap.io/api/v2. */ apiUrl?: string; } @@ -53,12 +53,15 @@ export interface LayerswapProviderConfig { * Metadata stored on the CryptoOnrampQuote returned by this provider. * * The swap is created at quote time, so we cache the swap id and deposit - * action here; `createDeposit` just reads them out. - */ + * action here. `createDeposit` just reads them out. */ export interface LayerswapQuoteMetadata { + /** Layerswap swap id created at quote time and reused by `createDeposit` / `getStatus`. */ swapId: string; + /** Pre-computed deposit address on the source chain that the user must send funds to. */ depositAddress: string; + /** Source-chain amount the user must send, in raw base units (e.g., wei). */ sourceAmountBaseUnits: string; + /** Target-chain amount the user receives, in raw base units (e.g., nanotons). */ targetAmountBaseUnits: string; } @@ -82,6 +85,10 @@ export class LayerswapCryptoOnrampProvider extends CryptoOnrampProvider createProvider(() => new LayerswapCryptoOnrampProvider(config)); diff --git a/packages/walletkit/src/defi/crypto-onramp/layerswap/README.md b/packages/walletkit/src/defi/crypto-onramp/layerswap/README.md index d05443a2f..d373c09aa 100644 --- a/packages/walletkit/src/defi/crypto-onramp/layerswap/README.md +++ b/packages/walletkit/src/defi/crypto-onramp/layerswap/README.md @@ -1,7 +1,7 @@ # Layerswap Crypto Onramp Provider @@ -37,7 +37,7 @@ See [Crypto Onramp README](../README.md) for base `CryptoOnrampQuoteParams`. Lay ```typescript const quote = await kit.cryptoOnramp.getQuote({ sourceCurrencyAddress: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9', // USDT on Arbitrum - sourceChain: 'eip155:42161', + sourceNetwork: '42161', targetCurrencyAddress: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs', // USDT on TON amount: '1000000', // 1 USDT (6 decimals) recipientAddress: 'UQ...', // TON address to receive tokens diff --git a/packages/walletkit/src/defi/crypto-onramp/layerswap/utils.ts b/packages/walletkit/src/defi/crypto-onramp/layerswap/utils.ts index d7d85f9d8..c8d3f2d3f 100644 --- a/packages/walletkit/src/defi/crypto-onramp/layerswap/utils.ts +++ b/packages/walletkit/src/defi/crypto-onramp/layerswap/utils.ts @@ -58,7 +58,7 @@ export const mapStatus = (status: LayerswapSwapStatus | string): CryptoOnrampSta /** * Format a base-units integer string into a decimal token-units string. - * e.g. formatBaseUnits('2000000', 6) === '2' + * e.g. formatBaseUnits('2000000', 6) === '2'. */ export const formatBaseUnits = (base: string, decimals: number): string => { if (!/^\d+$/.test(base)) { diff --git a/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/README.md b/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/README.md index 1adf4c6d5..8df8dde7f 100644 --- a/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/README.md +++ b/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/README.md @@ -1,7 +1,7 @@ # Swaps.xyz Crypto Onramp Provider @@ -48,7 +48,7 @@ import type { SwapsXyzQuoteOptions } from '@ton/walletkit/crypto-onramp/swaps-xy const quote = await kit.cryptoOnramp.getQuote({ sourceCurrencyAddress: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9', // USDT on Arbitrum - sourceChain: 'eip155:42161', + sourceNetwork: '42161', targetCurrencyAddress: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs', // USDT on TON amount: '1000000', // 1 USDT (6 decimals) recipientAddress: 'UQ...', // TON address to receive tokens diff --git a/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/SwapsXyzCryptoOnrampProvider.ts b/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/SwapsXyzCryptoOnrampProvider.ts index b566a2e5c..71e018c11 100644 --- a/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/SwapsXyzCryptoOnrampProvider.ts +++ b/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/SwapsXyzCryptoOnrampProvider.ts @@ -33,7 +33,7 @@ export interface SwapsXyzProviderConfig { apiKey: string; /** - * Override the base API URL. Defaults to https://api-v2.swaps.xyz/api + * Override the base API URL. Defaults to https://api-v2.swaps.xyz/api. */ apiUrl?: string; @@ -59,7 +59,9 @@ export interface SwapsXyzQuoteOptions { * CryptoOnrampDeposit without an extra network round-trip. */ export interface SwapsXyzQuoteMetadata { + /** EVM sender address swaps.xyz was quoted for. Required when later calling `createDeposit`. */ sender: string; + /** Raw `getAction` response cached at quote time so `createDeposit` doesn't need an extra round-trip. */ response: SwapsXyzGetActionResponse; } @@ -85,6 +87,10 @@ export class SwapsXyzCryptoOnrampProvider extends CryptoOnrampProvider createProvider(() => new SwapsXyzCryptoOnrampProvider(config)); diff --git a/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/utils.ts b/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/utils.ts index 9c555dad4..8a7138397 100644 --- a/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/utils.ts +++ b/packages/walletkit/src/defi/crypto-onramp/swaps-xyz/utils.ts @@ -13,7 +13,7 @@ import type { SwapsXyzErrorResponse } from './types'; const EVM_ADDRESS_REGEX = /^(0x)?[0-9a-fA-F]{40}$/; /** - * Extract a numeric EVM chain id from a CAIP-2 string. Returns `undefined` + * Extract a numeric EVM chain ID from a CAIP-2 string. Returns `undefined` * for non-EVM (`namespace !== 'eip155'`) or malformed values. */ export const parseEvmChainIdFromCaip2 = (value: string): number | undefined => { @@ -24,7 +24,7 @@ export const parseEvmChainIdFromCaip2 = (value: string): number | undefined => { }; /** - * Build the CAIP-2 representation for an EVM chain id. + * Build the CAIP-2 representation for an EVM chain ID. */ export const evmChainIdToCaip2 = (chainId: number | string): string => `eip155:${chainId}`; diff --git a/packages/walletkit/src/defi/errors.ts b/packages/walletkit/src/defi/errors.ts index c6698966c..a2fca24df 100644 --- a/packages/walletkit/src/defi/errors.ts +++ b/packages/walletkit/src/defi/errors.ts @@ -7,18 +7,34 @@ */ export enum DefiErrorCode { + /** Provider with the requested id is not registered with the manager. */ ProviderNotFound = 'PROVIDER_NOT_FOUND', + /** No default provider is configured and the caller did not specify one. */ NoDefaultProvider = 'NO_DEFAULT_PROVIDER', + /** Provider rejected the request because of an upstream/network failure. */ NetworkError = 'NETWORK_ERROR', + /** Provider does not support the network selected for the operation. */ UnsupportedNetwork = 'UNSUPPORTED_NETWORK', + /** Caller passed parameters that fail provider-level validation. */ InvalidParams = 'INVALID_PARAMS', + /** Provider failed its own internal validation and cannot be used. */ InvalidProvider = 'INVALID_PROVIDER', } +/** + * Base error thrown by DeFi managers (swap, staking, onramp) when a provider call fails. Subclassed by {@link SwapError} / {@link StakingError} / {@link CryptoOnrampError} and discriminated at runtime via the `code` field. + */ export class DefiError extends Error { + /** Stable error code for branching logic. Subclasses narrow this to their own domain-specific enum (e.g. {@link SwapErrorCode}, {@link StakingErrorCode}). */ public readonly code: string; + /** Provider-specific extra context (request payload, upstream error, etc.). Shape is not stable. */ public readonly details?: unknown; + /** + * @param message - Human-readable description, forwarded to `Error`. + * @param code - {@link DefiErrorCode} Stable error code for branching logic. + * @param details - Optional provider-specific context for diagnostics. + */ constructor(message: string, code: string, details?: unknown) { super(message); this.name = 'DefiError'; diff --git a/packages/walletkit/src/defi/onramp/errors.ts b/packages/walletkit/src/defi/onramp/errors.ts index a83067073..0d19ae078 100644 --- a/packages/walletkit/src/defi/onramp/errors.ts +++ b/packages/walletkit/src/defi/onramp/errors.ts @@ -9,9 +9,13 @@ import { DefiError } from '../errors'; export enum OnrampErrorCode { + /** Provider's upstream API rejected the call. */ ProviderError = 'PROVIDER_ERROR', + /** Caller passed parameters that fail provider-level validation. */ InvalidParams = 'INVALID_ONRAMP_PARAMS', + /** Provider could not produce a quote for the supplied parameters. */ QuoteFailed = 'QUOTE_FAILED', + /** Provider could not build the redirect URL for the requested onramp. */ UrlBuildFailed = 'URL_BUILD_FAILED', } diff --git a/packages/walletkit/src/defi/onramp/mercuryo/MercuryoProvider.ts b/packages/walletkit/src/defi/onramp/mercuryo/MercuryoProvider.ts index ec7974c69..0c2ac7419 100644 --- a/packages/walletkit/src/defi/onramp/mercuryo/MercuryoProvider.ts +++ b/packages/walletkit/src/defi/onramp/mercuryo/MercuryoProvider.ts @@ -12,7 +12,7 @@ import { OnrampProvider } from '../OnrampProvider'; import { OnrampError, OnrampErrorCode } from '../errors'; /** - * Custom options for Mercuryo requests + * Custom options for Mercuryo requests. */ export interface MercuryoQuoteOptions { /** @@ -24,18 +24,18 @@ export interface MercuryoQuoteOptions { export interface MercuryoOnrampOptions { /** - * E.g. The exact widget ID assigned by Mercuryo to the partner + * E.g. The exact widget ID assigned by Mercuryo to the partner. */ widgetId?: string; /** - * E.g. The user's email to pre-fill the widget + * E.g. The user's email to pre-fill the widget. */ merchantUserEmail?: string; } /** - * Provider implementation for Mercuryo onramp + * Provider implementation for Mercuryo onramp. */ export class MercuryoProvider extends OnrampProvider { readonly providerId = 'mercuryo'; @@ -48,7 +48,7 @@ export class MercuryoProvider extends OnrampProvider # Staking @@ -36,7 +36,7 @@ interface StakingQuoteParams { amount: TokenAmount; userAddress?: UserFriendlyAddress; network?: Network; - unstakeMode?: UnstakeModes; // unstake only; see UnstakeMode in @ton/walletkit + unstakeMode?: UnstakeModes; // unstake only. See UnstakeMode in @ton/walletkit providerOptions?: TProviderOptions; } ``` diff --git a/packages/walletkit/src/defi/staking/StakingManager.ts b/packages/walletkit/src/defi/staking/StakingManager.ts index d8dd51b9a..cb8a6bf50 100644 --- a/packages/walletkit/src/defi/staking/StakingManager.ts +++ b/packages/walletkit/src/defi/staking/StakingManager.ts @@ -30,6 +30,7 @@ const log = globalLogger.createChild('StakingManager'); * for staking operations. Providers can be switched dynamically. */ export class StakingManager extends DefiManager implements StakingAPI { + /** @param createFactoryContext - Lazy provider of the {@link ProviderFactoryContext} the manager passes into provider factories at registration time. */ constructor(createFactoryContext: () => ProviderFactoryContext) { super(createFactoryContext); } diff --git a/packages/walletkit/src/defi/staking/StakingProvider.ts b/packages/walletkit/src/defi/staking/StakingProvider.ts index f001868eb..e7899c5d4 100644 --- a/packages/walletkit/src/defi/staking/StakingProvider.ts +++ b/packages/walletkit/src/defi/staking/StakingProvider.ts @@ -26,6 +26,7 @@ export abstract class StakingProvider implements StakingProviderInterface { readonly type = 'staking'; readonly providerId: string; + /** @param providerId - Stable id the provider registers with — must be unique within {@link StakingManager}. */ constructor(providerId: string) { this.providerId = providerId; } diff --git a/packages/walletkit/src/defi/staking/errors.ts b/packages/walletkit/src/defi/staking/errors.ts index 2aa5754b1..b4cdd3914 100644 --- a/packages/walletkit/src/defi/staking/errors.ts +++ b/packages/walletkit/src/defi/staking/errors.ts @@ -9,13 +9,20 @@ import { DefiError } from '../errors'; export enum StakingErrorCode { + /** Caller passed parameters that fail provider-level validation. */ InvalidParams = 'INVALID_PARAMS', + /** Provider doesn't support the requested operation (e.g., reversed quote on a unidirectional pool). */ UnsupportedOperation = 'UNSUPPORTED_OPERATION', } export class StakingError extends DefiError { public readonly code: StakingErrorCode; + /** + * @param message - Human-readable description, forwarded to `Error`. + * @param code - {@link StakingErrorCode} Stable error code for branching logic. + * @param details - Optional provider-specific context for diagnostics. + */ constructor(message: string, code: StakingErrorCode, details?: unknown) { super(message, code, details); this.name = 'StakingError'; diff --git a/packages/walletkit/src/defi/staking/tonstakers/README.md b/packages/walletkit/src/defi/staking/tonstakers/README.md index 2c9f41e03..0e227f733 100644 --- a/packages/walletkit/src/defi/staking/tonstakers/README.md +++ b/packages/walletkit/src/defi/staking/tonstakers/README.md @@ -1,7 +1,7 @@ # Tonstakers staking provider @@ -20,7 +20,7 @@ import type { TonStakersProviderConfig } from '@ton/walletkit/staking/tonstakers const config: TonStakersProviderConfig = { [Network.mainnet().chainId]: { - contractAddress: 'EQ...', // optional; defaults to known pool when available + contractAddress: 'EQ...', // optional. Defaults to known pool when available tonApiToken: '...', // optional TonAPI key for APY (`getStakingProviderInfo`) }, }; @@ -37,10 +37,10 @@ Networks without a known Tonstakers pool and without `contractAddress` are skipp | Value | Behavior | |-------|----------| | `UnstakeMode.INSTANT` | Immediate exit if the pool has liquidity (`fillOrKill`) | -| `UnstakeMode.WHEN_AVAILABLE` | Non–fill-or-kill; completes when liquidity allows | +| `UnstakeMode.WHEN_AVAILABLE` | Non–fill-or-kill — completes when liquidity allows | | `UnstakeMode.ROUND_END` | Wait until round end for the projected rate (`waitTillRoundEnd`) | -`getSupportedUnstakeModes()` returns these three values. Quote and transaction building must use the same `unstakeMode` on the quote; if it is missing on an unstake quote, the provider defaults to **`UnstakeMode.INSTANT`**. +`getSupportedUnstakeModes()` returns these three values. Quote and transaction building must use the same `unstakeMode` on the quote. If it is missing on an unstake quote, the provider defaults to **`UnstakeMode.INSTANT`**. ## Balances and pool info diff --git a/packages/walletkit/src/defi/staking/tonstakers/TonStakersStakingProvider.ts b/packages/walletkit/src/defi/staking/tonstakers/TonStakersStakingProvider.ts index eff9e5c29..d02828f10 100644 --- a/packages/walletkit/src/defi/staking/tonstakers/TonStakersStakingProvider.ts +++ b/packages/walletkit/src/defi/staking/tonstakers/TonStakersStakingProvider.ts @@ -40,7 +40,7 @@ const log = globalLogger.createChild('TonStakersStakingProvider'); * - Unstake: Burn tsTON to withdraw TON with {@link UnstakeMode} values: * - `INSTANT` – immediate withdrawal if the pool has liquidity (`fillOrKill`) * - `WHEN_AVAILABLE` – withdraw when liquidity is available (non–fill-or-kill) - * - `ROUND_END` – wait until round end for the projected rate + * - `ROUND_END` – wait until round end for the projected rate. */ export class TonStakersStakingProvider extends StakingProvider { private readonly networkManager: NetworkManager; @@ -510,6 +510,8 @@ export class TonStakersStakingProvider extends StakingProvider { /** * Returns an AppKit / `ProviderInput` factory: pass to `providers: [createTonstakersProvider(config)]`. * At kit init, the factory receives context and builds the provider using `ctx.networkManager` for RPC. + * + * @param config - Optional {@link TonStakersProviderConfig}. Defaults are filled in for any field left undefined. */ export const createTonstakersProvider = ( config: TonStakersProviderConfig = {}, diff --git a/packages/walletkit/src/defi/staking/tonstakers/index.ts b/packages/walletkit/src/defi/staking/tonstakers/index.ts index b77e1c2db..34af35d20 100644 --- a/packages/walletkit/src/defi/staking/tonstakers/index.ts +++ b/packages/walletkit/src/defi/staking/tonstakers/index.ts @@ -7,4 +7,4 @@ */ export { TonStakersStakingProvider, createTonstakersProvider } from './TonStakersStakingProvider'; -export type { TonStakersProviderConfig } from './models/TonStakersProviderConfig'; +export type { TonStakersProviderConfig, TonStakersChainConfig } from './models/TonStakersProviderConfig'; diff --git a/packages/walletkit/src/defi/staking/tonstakers/models/TonStakersProviderConfig.ts b/packages/walletkit/src/defi/staking/tonstakers/models/TonStakersProviderConfig.ts index 57e2bc56e..a8be2c240 100644 --- a/packages/walletkit/src/defi/staking/tonstakers/models/TonStakersProviderConfig.ts +++ b/packages/walletkit/src/defi/staking/tonstakers/models/TonStakersProviderConfig.ts @@ -9,19 +9,15 @@ import type { StakingProviderMetadataOverride } from '../../../../api/models'; export interface TonStakersChainConfig { - /** - * optional TonAPI key for APY requests only. If not provided, APY will be available, but if you're using TonAPI, it's recommended to provide the key. - */ + /** TonAPI key used for APY reads. Optional — APY still works without it, but providing one is recommended when you already use TonAPI elsewhere. */ tonApiToken?: string; - /** - * optional override to customize provider metadata. - */ + /** Optional {@link StakingProviderMetadataOverride} applied on top of the built-in Tonstakers metadata for this chain. */ metadata?: StakingProviderMetadataOverride; } /** - * Configuration for TonStakersStakingProvider + * Configuration for TonStakersStakingProvider — map of chain ID to per-chain {@link TonStakersChainConfig}. */ -export interface TonStakersProviderConfig { +export type TonStakersProviderConfig = { [chainId: string]: TonStakersChainConfig; -} +}; diff --git a/packages/walletkit/src/defi/staking/tonstakers/models/index.ts b/packages/walletkit/src/defi/staking/tonstakers/models/index.ts index 5c9626354..f18f763ca 100644 --- a/packages/walletkit/src/defi/staking/tonstakers/models/index.ts +++ b/packages/walletkit/src/defi/staking/tonstakers/models/index.ts @@ -6,4 +6,4 @@ * */ -export type { TonStakersProviderConfig } from './TonStakersProviderConfig'; +export type { TonStakersProviderConfig, TonStakersChainConfig } from './TonStakersProviderConfig'; diff --git a/packages/walletkit/src/defi/swap/README.md b/packages/walletkit/src/defi/swap/README.md index c56e2bd36..85994d376 100644 --- a/packages/walletkit/src/defi/swap/README.md +++ b/packages/walletkit/src/defi/swap/README.md @@ -1,7 +1,7 @@ # Swap Manager diff --git a/packages/walletkit/src/defi/swap/SwapManager.ts b/packages/walletkit/src/defi/swap/SwapManager.ts index 3ae1da73a..1c4d55493 100644 --- a/packages/walletkit/src/defi/swap/SwapManager.ts +++ b/packages/walletkit/src/defi/swap/SwapManager.ts @@ -24,6 +24,7 @@ const log = globalLogger.createChild('SwapManager'); * for swap operations. Providers can be switched dynamically. */ export class SwapManager extends DefiManager implements SwapAPI { + /** @param createFactoryContext - Lazy provider of the {@link ProviderFactoryContext} the manager passes into provider factories at registration time. */ constructor(createFactoryContext: () => ProviderFactoryContext) { super(createFactoryContext); } diff --git a/packages/walletkit/src/defi/swap/SwapProvider.ts b/packages/walletkit/src/defi/swap/SwapProvider.ts index 8201f748b..d16d1dd0c 100644 --- a/packages/walletkit/src/defi/swap/SwapProvider.ts +++ b/packages/walletkit/src/defi/swap/SwapProvider.ts @@ -17,23 +17,9 @@ import type { import type { SwapProviderInterface } from '../../api/interfaces'; /** - * Abstract base class for swap providers + * Abstract base class for swap providers. * - * Provides a common interface for implementing swap functionality - * across different DEXs and protocols. - * - * @example - * ```typescript - * class MySwapProvider extends SwapProvider { - * async getQuote(params: SwapQuoteParams): Promise { - * // Implementation - * } - * - * async buildSwapTransaction(params: SwapParams): Promise { - * // Implementation - * } - * } - * ``` + * Provides a common interface for implementing swap functionality across different DEXs and protocols. Apps don't typically subclass it directly — use the bundled factories ({@link createDeDustProvider}, {@link createOmnistonProvider}) or build a custom provider through `createProvider`. */ export abstract class SwapProvider< TQuoteOptions = undefined, @@ -63,7 +49,7 @@ export abstract class SwapProvider< abstract buildSwapTransaction(params: SwapParams): Promise; /** - * Get provider metadata + * Get provider metadata. */ abstract getMetadata(): SwapProviderMetadata; } diff --git a/packages/walletkit/src/defi/swap/dedust/DeDustPrivateTypes.ts b/packages/walletkit/src/defi/swap/dedust/DeDustPrivateTypes.ts index d273d2a9a..98d1ecd88 100644 --- a/packages/walletkit/src/defi/swap/dedust/DeDustPrivateTypes.ts +++ b/packages/walletkit/src/defi/swap/dedust/DeDustPrivateTypes.ts @@ -7,7 +7,7 @@ */ /** - * Route step from DeDust Router API + * Route step from DeDust Router API. */ export interface DeDustRouteStep { pool_address: string; @@ -26,7 +26,7 @@ export interface DeDustRouteStep { } /** - * Swap data from DeDust Router API quote response + * Swap data from DeDust Router API quote response. */ export interface DeDustSwapData { slippage_bps: number; @@ -34,7 +34,7 @@ export interface DeDustSwapData { } /** - * Quote response from DeDust Router API + * Quote response from DeDust Router API. */ export interface DeDustQuoteResponse { in_amount: string; @@ -48,7 +48,7 @@ export interface DeDustQuoteResponse { } /** - * Swap request to DeDust Router API + * Swap request to DeDust Router API. */ export interface DeDustSwapRequest { sender_address: string; @@ -63,7 +63,7 @@ export interface DeDustSwapRequest { } /** - * Swap transaction from DeDust Router API + * Swap transaction from DeDust Router API. */ export interface DeDustSwapTransaction { address: string; @@ -73,7 +73,7 @@ export interface DeDustSwapTransaction { } /** - * Swap response from DeDust Router API + * Swap response from DeDust Router API. */ export interface DeDustSwapResponse { query_id: number; diff --git a/packages/walletkit/src/defi/swap/dedust/DeDustSwapProvider.ts b/packages/walletkit/src/defi/swap/dedust/DeDustSwapProvider.ts index fe44aacc6..be728db05 100644 --- a/packages/walletkit/src/defi/swap/dedust/DeDustSwapProvider.ts +++ b/packages/walletkit/src/defi/swap/dedust/DeDustSwapProvider.ts @@ -29,12 +29,12 @@ import type { ProviderFactoryContext } from '../../../types/factory'; const log = globalLogger.createChild('DeDustSwapProvider'); /** - * Default API URL for DeDust Router + * Default API URL for DeDust Router. */ const DEFAULT_API_URL = 'https://api-mainnet.dedust.io'; /** - * Default protocols to use for routing + * Default protocols to use for routing. */ const DEFAULT_PROTOCOLS = [ 'dedust', @@ -53,18 +53,7 @@ const DEFAULT_PROTOCOLS = [ * Uses the DeDust Router API to get quotes and build swap transactions * with optimal routing across multiple pools and protocols. * - * @example - * ```typescript - * import { createDeDustProvider } from '@ton/walletkit/swap/dedust'; - * - * kit.swap.registerProvider( - * createDeDustProvider({ - * defaultSlippageBps: 100, // 1% - * referralAddress: 'EQ...', - * referralFeeBps: 50, // 0.5% - * }), - * ); - * ``` + * @sample docs/examples/src/appkit/swap#DEDUST_QUICK_START */ export class DeDustSwapProvider extends SwapProvider { private readonly apiUrl: string; @@ -83,6 +72,10 @@ export class DeDustSwapProvider extends SwapProvider # DeDust Swap Provider diff --git a/packages/walletkit/src/defi/swap/dedust/models/DeDustProviderOptions.ts b/packages/walletkit/src/defi/swap/dedust/models/DeDustProviderOptions.ts index 940c610f4..546bdb3f0 100644 --- a/packages/walletkit/src/defi/swap/dedust/models/DeDustProviderOptions.ts +++ b/packages/walletkit/src/defi/swap/dedust/models/DeDustProviderOptions.ts @@ -9,23 +9,21 @@ import type { DeDustReferralOptions } from './DeDustReferralOptions'; /** - * Provider-specific options for DeDust swap operations + * Provider-specific options for DeDust swap operations. */ export interface DeDustProviderOptions extends DeDustReferralOptions { /** - * Protocols to use for routing - * Available: 'dedust', 'dedust_v3', 'dedust_v3_memepad', 'stonfi_v1', 'stonfi_v2', 'tonco', 'memeslab', 'tonfun' - * @default all protocols + * Protocols to use for routing. Available values: `'dedust'`, `'dedust_v3'`, `'dedust_v3_memepad'`, `'stonfi_v1'`, `'stonfi_v2'`, `'tonco'`, `'memeslab'`, `'tonfun'`. Defaults to all protocols when omitted. */ protocols?: string[]; /** - * Protocols to exclude from routing + * Protocols to exclude from routing. */ excludeProtocols?: string[]; /** - * Only use verified pools + * Only use verified pools. */ onlyVerifiedPools?: boolean; @@ -42,7 +40,7 @@ export interface DeDustProviderOptions extends DeDustReferralOptions { maxLength?: number; /** - * Exclude volatile pools + * Exclude volatile pools. */ excludeVolatilePools?: boolean; } diff --git a/packages/walletkit/src/defi/swap/dedust/models/DeDustQuoteMetadata.ts b/packages/walletkit/src/defi/swap/dedust/models/DeDustQuoteMetadata.ts index be174aca0..2c6ba3f2d 100644 --- a/packages/walletkit/src/defi/swap/dedust/models/DeDustQuoteMetadata.ts +++ b/packages/walletkit/src/defi/swap/dedust/models/DeDustQuoteMetadata.ts @@ -9,7 +9,7 @@ import type { DeDustQuoteResponse } from '../DeDustPrivateTypes'; /** - * Metadata stored in SwapQuote for DeDust provider + * Metadata stored in SwapQuote for DeDust provider. */ export interface DeDustQuoteMetadata { /** diff --git a/packages/walletkit/src/defi/swap/dedust/models/DeDustReferralOptions.ts b/packages/walletkit/src/defi/swap/dedust/models/DeDustReferralOptions.ts index 97c9e97ce..09f4e8aff 100644 --- a/packages/walletkit/src/defi/swap/dedust/models/DeDustReferralOptions.ts +++ b/packages/walletkit/src/defi/swap/dedust/models/DeDustReferralOptions.ts @@ -7,11 +7,11 @@ */ /** - * Options for configuring the referral in DeDust swap operations + * Options for configuring the referral in DeDust swap operations. */ export interface DeDustReferralOptions { /** - * The address of the referrer + * The address of the referrer. */ referralAddress?: string; diff --git a/packages/walletkit/src/defi/swap/dedust/models/DeDustSwapProviderConfig.ts b/packages/walletkit/src/defi/swap/dedust/models/DeDustSwapProviderConfig.ts index 8f26878dc..7f9d1935b 100644 --- a/packages/walletkit/src/defi/swap/dedust/models/DeDustSwapProviderConfig.ts +++ b/packages/walletkit/src/defi/swap/dedust/models/DeDustSwapProviderConfig.ts @@ -10,7 +10,7 @@ import type { SwapProviderMetadataOverride } from '../../../../api/models'; import type { DeDustReferralOptions } from './DeDustReferralOptions'; /** - * Configuration for the DeDust Swap Provider + * Configuration for the DeDust Swap Provider. */ export interface DeDustSwapProviderConfig extends DeDustReferralOptions { /** @@ -59,7 +59,7 @@ export interface DeDustSwapProviderConfig extends DeDustReferralOptions { minPoolUsdTvl?: string; /** - * Custom metadata for the provider + * Custom metadata for the provider. */ metadata?: SwapProviderMetadataOverride; } diff --git a/packages/walletkit/src/defi/swap/dedust/utils.ts b/packages/walletkit/src/defi/swap/dedust/utils.ts index fa51d54cd..083c6c6bd 100644 --- a/packages/walletkit/src/defi/swap/dedust/utils.ts +++ b/packages/walletkit/src/defi/swap/dedust/utils.ts @@ -13,7 +13,7 @@ import type { DeDustQuoteMetadata } from './models'; import type { SwapToken } from '../../../api/models'; /** - * Native TON identifier used by DeDust Router API + * Native TON identifier used by DeDust Router API. */ export const NATIVE_TON_MINTER = 'native'; @@ -30,7 +30,7 @@ export const tokenToMinter = (token: SwapToken): string => { }; /** - * Convert DeDust minter address string to SwapToken + * Convert DeDust minter address string to SwapToken. */ export const minterToToken = (minter: string, decimals: number = 9): SwapToken => { if (minter === NATIVE_TON_MINTER) { @@ -45,7 +45,7 @@ export const minterToToken = (minter: string, decimals: number = 9): SwapToken = }; /** - * Check if token is native TON + * Check if token is native TON. */ export const isNativeTon = (token: SwapToken): boolean => { return token.address === 'ton'; @@ -61,7 +61,7 @@ export const validateNetwork = (network: Network): void => { }; /** - * Type guard for DeDustQuoteMetadata + * Type guard for DeDustQuoteMetadata. */ export const isDeDustQuoteMetadata = (metadata: unknown): metadata is DeDustQuoteMetadata => { if (!metadata || typeof metadata !== 'object') { diff --git a/packages/walletkit/src/defi/swap/errors.ts b/packages/walletkit/src/defi/swap/errors.ts index 41e775e21..5ff7061e7 100644 --- a/packages/walletkit/src/defi/swap/errors.ts +++ b/packages/walletkit/src/defi/swap/errors.ts @@ -9,16 +9,26 @@ import { DefiError } from '../errors'; export enum SwapErrorCode { + /** Provider returned malformed or missing quote data. */ InvalidQuote = 'INVALID_QUOTE', + /** No route or pool has enough liquidity to satisfy the requested swap. */ InsufficientLiquidity = 'INSUFFICIENT_LIQUIDITY', + /** Quote payload is too old to use. Fetch a new one before building the transaction. */ QuoteExpired = 'QUOTE_EXPIRED', + /** Provider failed to produce a swap transaction from the supplied quote. */ BuildTxFailed = 'BUILD_TX_FAILED', + /** Provider rejected the request because of an upstream/network failure. */ NetworkError = 'NETWORK_ERROR', } export class SwapError extends DefiError { public readonly code: SwapErrorCode; + /** + * @param message - Human-readable description, forwarded to `Error`. + * @param code - {@link SwapErrorCode} Stable error code for branching logic. + * @param details - Optional provider-specific context for diagnostics. + */ constructor(message: string, code: SwapErrorCode, details?: unknown) { super(message, code, details); this.name = 'SwapError'; diff --git a/packages/walletkit/src/defi/swap/omniston/OmnistonSwapProvider.ts b/packages/walletkit/src/defi/swap/omniston/OmnistonSwapProvider.ts index 897227a1a..fd01cb0bf 100644 --- a/packages/walletkit/src/defi/swap/omniston/OmnistonSwapProvider.ts +++ b/packages/walletkit/src/defi/swap/omniston/OmnistonSwapProvider.ts @@ -30,20 +30,7 @@ const log = globalLogger.createChild('OmnistonSwapProvider'); * Uses the Omniston SDK to get quotes and build swap transactions * across multiple DEXs on TON blockchain. * - * @example - * ```typescript - * // Import from a separate entry point to avoid bundling the Omniston SDK - * import { createOmnistonProvider } from '@ton/walletkit/swap/omniston'; - * - * kit.swap.registerProvider( - * createOmnistonProvider({ - * apiUrl: 'wss://omni-ws.ston.fi', - * defaultSlippageBps: 100, // 1% - * referrerAddress: 'EQ...', - * referrerFeeBps: 10, // 0.1% - * }), - * ); - * ``` + * @sample docs/examples/src/appkit/swap#OMNISTON_QUICK_START */ export class OmnistonSwapProvider extends SwapProvider { private readonly apiUrl: string; @@ -60,6 +47,10 @@ export class OmnistonSwapProvider extends SwapProvider readonly providerId: string; + /** + * @param config - Optional {@link OmnistonSwapProviderConfig}. Defaults are filled in for any field left undefined. + * @expand config + */ constructor(config?: OmnistonSwapProviderConfig) { super(); this.providerId = config?.providerId ?? 'omniston'; @@ -339,6 +330,9 @@ export class OmnistonSwapProvider extends SwapProvider /** * Returns an AppKit / `ProviderInput` factory for {@link OmnistonSwapProvider}: * pass to `providers: [createOmnistonProvider(config)]`. + * + * @param config - Optional {@link OmnistonSwapProviderConfig}. Defaults are filled in for any field left undefined. + * @expand config */ export const createOmnistonProvider = ( config: OmnistonSwapProviderConfig = {}, diff --git a/packages/walletkit/src/defi/swap/omniston/README.md b/packages/walletkit/src/defi/swap/omniston/README.md index 460dfd939..9f96e7273 100644 --- a/packages/walletkit/src/defi/swap/omniston/README.md +++ b/packages/walletkit/src/defi/swap/omniston/README.md @@ -1,7 +1,7 @@ # Omniston Swap Provider @@ -35,7 +35,7 @@ interface OmnistonSwapProviderConfig { } ``` -**Omniston-specific quote options:** `maxOutgoingMessages` (max messages per tx; default 1). Extract from wallet features via `getMaxOutgoingMessages()`. See [Swap README](../README.md) for base parameters. +**Omniston-specific quote options:** `maxOutgoingMessages` (max messages per tx, default 1). Extract from wallet features via `getMaxOutgoingMessages()`. See [Swap README](../README.md) for base parameters. ### Usage Example diff --git a/packages/walletkit/src/defi/swap/omniston/models/OmnistonProviderOptions.ts b/packages/walletkit/src/defi/swap/omniston/models/OmnistonProviderOptions.ts index 053cb4426..ae6602e90 100644 --- a/packages/walletkit/src/defi/swap/omniston/models/OmnistonProviderOptions.ts +++ b/packages/walletkit/src/defi/swap/omniston/models/OmnistonProviderOptions.ts @@ -10,6 +10,6 @@ import type { OmnistonReferrerOptions } from './OmnistonReferrerOptions'; import type { OmnistonSwapOptions } from './OmnistonSwapOptions'; /** - * Provider-specific options for Omniston swap operations + * Provider-specific options for Omniston swap operations. */ export type OmnistonProviderOptions = OmnistonSwapOptions & OmnistonReferrerOptions; diff --git a/packages/walletkit/src/defi/swap/omniston/models/OmnistonQuoteMetadata.ts b/packages/walletkit/src/defi/swap/omniston/models/OmnistonQuoteMetadata.ts index 5e26e5fda..089effeeb 100644 --- a/packages/walletkit/src/defi/swap/omniston/models/OmnistonQuoteMetadata.ts +++ b/packages/walletkit/src/defi/swap/omniston/models/OmnistonQuoteMetadata.ts @@ -9,11 +9,11 @@ import type { Quote } from '@ston-fi/omniston-sdk'; /** - * Metadata associated with an Omniston quote + * Metadata associated with an Omniston quote. */ export interface OmnistonQuoteMetadata { /** - * The actual omniston quote object + * The actual Omniston quote object * @format frozen */ omnistonQuote: Quote; diff --git a/packages/walletkit/src/defi/swap/omniston/models/OmnistonReferrerOptions.ts b/packages/walletkit/src/defi/swap/omniston/models/OmnistonReferrerOptions.ts index 27c8e0d9b..0bbd9228b 100644 --- a/packages/walletkit/src/defi/swap/omniston/models/OmnistonReferrerOptions.ts +++ b/packages/walletkit/src/defi/swap/omniston/models/OmnistonReferrerOptions.ts @@ -7,11 +7,11 @@ */ /** - * Options for configuring the referrer in Omniston swap operations + * Options for configuring the referrer in Omniston swap operations. */ export interface OmnistonReferrerOptions { /** - * The address of the referrer + * The address of the referrer. */ referrerAddress?: string; @@ -22,7 +22,7 @@ export interface OmnistonReferrerOptions { referrerFeeBps?: number; /** - * Whether a flexible referrer fee is allowed + * Whether a flexible referrer fee is allowed. */ flexibleReferrerFee?: boolean; } diff --git a/packages/walletkit/src/defi/swap/omniston/models/OmnistonSwapOptions.ts b/packages/walletkit/src/defi/swap/omniston/models/OmnistonSwapOptions.ts index a4337696d..0b91cccb6 100644 --- a/packages/walletkit/src/defi/swap/omniston/models/OmnistonSwapOptions.ts +++ b/packages/walletkit/src/defi/swap/omniston/models/OmnistonSwapOptions.ts @@ -22,7 +22,7 @@ export type SettlementMethodValue = (typeof SettlementMethod)[keyof typeof Settl export type OmnistonSwapOptions = { /** - * Settlement methods to use for the swap + * Settlement methods to use for the swap. */ settlementMethods?: SettlementMethodValue[]; }; diff --git a/packages/walletkit/src/defi/swap/omniston/models/OmnistonSwapProviderConfig.ts b/packages/walletkit/src/defi/swap/omniston/models/OmnistonSwapProviderConfig.ts index 1d4454b57..51a98ea2f 100644 --- a/packages/walletkit/src/defi/swap/omniston/models/OmnistonSwapProviderConfig.ts +++ b/packages/walletkit/src/defi/swap/omniston/models/OmnistonSwapProviderConfig.ts @@ -10,7 +10,7 @@ import type { SwapProviderMetadataOverride } from '../../../../api/models'; import type { OmnistonReferrerOptions } from './OmnistonReferrerOptions'; /** - * Configuration for the Omniston Swap Provider + * Configuration for the Omniston Swap Provider. */ export interface OmnistonSwapProviderConfig extends OmnistonReferrerOptions { /** @@ -32,12 +32,12 @@ export interface OmnistonSwapProviderConfig extends OmnistonReferrerOptions { quoteTimeoutMs?: number; /** - * Identifier for the provider + * Identifier for the provider. */ providerId?: string; /** - * Custom metadata for the provider + * Custom metadata for the provider. */ metadata?: SwapProviderMetadataOverride; } diff --git a/packages/walletkit/src/index.ts b/packages/walletkit/src/index.ts index a0920c91e..39e42c40e 100644 --- a/packages/walletkit/src/index.ts +++ b/packages/walletkit/src/index.ts @@ -33,6 +33,7 @@ export { EventEmitter } from './core/EventEmitter'; export type { EventListener, EventPayload, KitEvent } from './core/EventEmitter'; export type { SharedKitEvents } from './types/emitter'; export { ApiClientToncenter } from './clients/toncenter'; +export type { ApiClientToncenterConfig, BaseApiClientConfig } from './clients/toncenter'; export { ApiClientTonApi } from './clients/tonapi'; export type { NetworkManager } from './core/NetworkManager'; export { KitNetworkManager } from './core/NetworkManager'; diff --git a/packages/walletkit/src/types/config.ts b/packages/walletkit/src/types/config.ts index 3acad1afe..82d2a7a94 100644 --- a/packages/walletkit/src/types/config.ts +++ b/packages/walletkit/src/types/config.ts @@ -17,34 +17,37 @@ import type { AnalyticsManagerOptions } from '../analytics'; import type { TONConnectSessionManager } from '../api/interfaces'; /** - * API client configuration options + * API client configuration options. */ export interface ApiClientConfig { - url?: string; // default 'https://toncenter.com' for mainnet, 'https://testnet.toncenter.com' for testnet - key?: string; // key for better RPS limits + /** Base URL of the indexer endpoint. Defaults to `'https://toncenter.com'` for mainnet, `'https://testnet.toncenter.com'` for testnet. */ + url?: string; + /** API key forwarded to the indexer for higher rate limits. */ + key?: string; } /** - * Network configuration for a specific chain + * Network configuration for a specific chain. */ export interface NetworkConfig { - /** API client configuration or instance */ + /** API client configuration or instance. */ apiClient?: ApiClientConfig | ApiClient; } /** - * Multi-network configuration keyed by chain ID - * Example: { [Networl.mainnet().chainId]: { apiClient: {...} }, [Networl.testnet().chainId]: { apiClient: {...} } } + * Multi-network configuration keyed by chain ID — each entry maps a chain ID (e.g. `Network.mainnet().chainId`) to its own {@link NetworkConfig} carrying the api-client setup. */ export type NetworkAdapters = { [key: string]: NetworkConfig | undefined; }; /** - * Main configuration options for TonWalletKit + * Main configuration options for TonWalletKit. */ export interface TonWalletKitOptions { + /** TonConnect wallet manifest published by the dApp. Required for the wallet to recognize the integration. */ walletManifest?: WalletInfo; + /** Device fingerprint forwarded with TonConnect requests so wallets can recognize the host. */ deviceInfo?: DeviceInfo; /** @@ -54,26 +57,28 @@ export interface TonWalletKitOptions { sessionManager?: TONConnectSessionManager; /** - * Network configuration + * Network configuration. */ networks?: NetworkAdapters; - /** Bridge settings */ + /** Bridge settings. */ bridge?: BridgeConfig; - /** Storage settings */ + /** Storage settings. */ storage?: StorageConfig | StorageAdapter; - /** Validation settings */ + /** Validation settings. */ validation?: { strictMode?: boolean; allowUnknownWalletVersions?: boolean; }; - /** Event processor settings */ + /** Event processor settings. */ eventProcessor?: EventProcessorConfig; + /** Analytics manager options merged with an `enabled` toggle. Off by default. */ analytics?: AnalyticsManagerOptions & { enabled?: boolean; }; + /** Diagnostic toggles useful during local development. Should not be set in production builds. */ dev?: { disableNetworkSend?: boolean; disableManifestDomainCheck?: boolean; diff --git a/packages/walletkit/src/types/durableEvents.ts b/packages/walletkit/src/types/durableEvents.ts index cc64f6b16..50aa08222 100644 --- a/packages/walletkit/src/types/durableEvents.ts +++ b/packages/walletkit/src/types/durableEvents.ts @@ -12,27 +12,27 @@ import type { WalletId } from '../utils/walletId'; import type { RawBridgeEvent, EventType } from './internal'; /** - * Event processing states + * Event processing states. */ export type EventStatus = 'new' | 'processing' | 'completed' | 'errored'; /** - * Stored event with metadata + * Stored event with metadata. */ export interface StoredEvent { - /** Unique event identifier */ + /** Unique event identifier. */ id: string; - /** Session ID associated with the event */ + /** Session ID associated with the event. */ sessionId?: string; - /** Type of bridge event */ + /** Type of bridge event. */ eventType: EventType; - /** Original raw bridge event data */ + /** Original raw bridge event data. */ rawEvent: RawBridgeEvent; - /** Current processing status */ + /** Current processing status. */ status: EventStatus; /** Timestamp when event was received (Unix timestamp) */ @@ -44,44 +44,44 @@ export interface StoredEvent { /** Timestamp when processing completed (Unix timestamp) */ completedAt?: number; - /** Wallet address that has locked this event for processing */ + /** Wallet address that has locked this event for processing. */ lockedBy?: string; - /** Size of the event in bytes */ + /** Size of the event in bytes. */ sizeBytes: number; - /** Number of retry attempts made for this event */ + /** Number of retry attempts made for this event. */ retryCount?: number; - /** Last error message encountered during processing */ + /** Last error message encountered during processing. */ lastError?: string; } /** - * Configuration for durable events + * Configuration for durable events. */ export interface DurableEventsConfig { - /** Interval for loop in milliseconds */ + /** Interval for loop in milliseconds. */ recoveryIntervalMs: number; - /** Timeout after which event is considered stale and will be recovered */ + /** Timeout after which event is considered stale and will be recovered. */ processingTimeoutMs: number; - /** Interval for cleanup process in milliseconds */ + /** Interval for cleanup process in milliseconds. */ cleanupIntervalMs: number; - /** How long to retain events in milliseconds */ + /** How long to retain events in milliseconds. */ retentionMs: number; - /** Delay between retry attempts in milliseconds */ + /** Delay between retry attempts in milliseconds. */ retryDelayMs: number; - /** Maximum number of retry attempts before marking event as errored */ + /** Maximum number of retry attempts before marking event as errored. */ maxRetries: number; } /** - * Default configuration for durable events + * Default configuration for durable events. */ export const DEFAULT_DURABLE_EVENTS_CONFIG: DurableEventsConfig = { recoveryIntervalMs: 10 * 1000, // 10 seconds @@ -93,16 +93,16 @@ export const DEFAULT_DURABLE_EVENTS_CONFIG: DurableEventsConfig = { }; /** - * Event store interface for persistent storage of bridge events + * Event store interface for persistent storage of bridge events. */ export interface EventStore { /** - * Store a new event from the bridge + * Store a new event from the bridge. */ storeEvent(rawEvent: RawBridgeEvent): Promise; /** - * Get events for a wallet that are ready for processing + * Get events for a wallet that are ready for processing. */ getEventsForWallet(sessionIds: string[], eventTypes: EventType[]): Promise; @@ -113,34 +113,34 @@ export interface EventStore { /** * Attempt to acquire exclusive lock on an event for processing - * Returns true if lock acquired, false if already locked + * Returns true if lock acquired, false if already locked. */ acquireLock(eventId: string, walletId: WalletId): Promise; /** - * Release lock on an event and increment retry count if error is provided + * Release lock on an event and increment retry count if error is provided. */ releaseLock(eventId: string, error?: string): Promise; /** - * Update event status and timestamps with optimistic locking + * Update event status and timestamps with optimistic locking. */ updateEventStatus(eventId: string, status: EventStatus, oldStatus: EventStatus): Promise; /** - * Get event by ID + * Get event by ID. */ getEvent(eventId: string): Promise; /** * Recover stale events that have been processing too long - * Returns number of events recovered + * Returns number of events recovered. */ recoverStaleEvents(processingTimeoutMs: number): Promise; /** * Clean up old completed events - * Returns number of events cleaned up + * Returns number of events cleaned up. */ cleanupOldEvents(retentionMs: number): Promise; @@ -151,31 +151,31 @@ export interface EventStore { } /** - * Event processor interface for consuming durable events + * Event processor interface for consuming durable events. */ export interface EventProcessor { /** - * Start processing events for a wallet + * Start processing events for a wallet. */ startProcessing(walletAddress: string): Promise; /** - * Stop processing events for a wallet + * Stop processing events for a wallet. */ stopProcessing(walletAddress: string): Promise; /** - * Mark an event as completed after successful processing + * Mark an event as completed after successful processing. */ completeEvent(eventId: string): Promise; /** - * Start the recovery process for stale events + * Start the recovery process for stale events. */ startRecoveryLoop(): void; /** - * Stop the recovery process + * Stop the recovery process. */ stopRecoveryLoop(): void; } diff --git a/packages/walletkit/src/types/factory.ts b/packages/walletkit/src/types/factory.ts index af0446664..501d6199b 100644 --- a/packages/walletkit/src/types/factory.ts +++ b/packages/walletkit/src/types/factory.ts @@ -15,18 +15,19 @@ import type { SharedKitEvents } from './emitter'; * Context passed to provider factory functions. */ export interface ProviderFactoryContext { + /** Network manager the provider should use for client lookups and default-network reads. */ networkManager: NetworkManager; + /** Event emitter the provider should publish its events to. */ eventEmitter: EventEmitter; - ssr?: boolean; } -/** Factory function that creates a provider from context */ +/** Factory function that creates a provider from context. */ export type ProviderFactory = (ctx: ProviderFactoryContext) => T; -/** A provider instance or a factory that creates one */ +/** A provider instance or a factory that creates one. */ export type ProviderInput = T | ProviderFactory; -/** Helper for creating typed provider factories */ +/** Helper for creating typed provider factories. */ export function createProvider(factory: ProviderFactory): ProviderFactory { return factory; } diff --git a/packages/walletkit/src/types/internal.ts b/packages/walletkit/src/types/internal.ts index 4ac6dcf99..ae6fe874d 100644 --- a/packages/walletkit/src/types/internal.ts +++ b/packages/walletkit/src/types/internal.ts @@ -109,7 +109,7 @@ export function toExtraCurrencies(extraCurrency: ConnectExtraCurrency | undefine } /** - * Raw transaction params as received from TON Connect protocol + * Raw transaction params as received from TON Connect protocol. */ export interface RawConnectTransactionParamContent { messages: ConnectTransactionParamMessage[]; @@ -126,7 +126,7 @@ export interface ConnectTransactionParamContent { } /** - * Parse raw TON Connect transaction params to internal format + * Parse raw TON Connect transaction params to internal format. */ export function parseConnectTransactionParamContent( raw: RawConnectTransactionParamContent, @@ -177,7 +177,7 @@ export function toTransactionRequest(params: ConnectTransactionParamContent): Tr } /** - * Convert internal TransactionRequest to raw TON Connect protocol + * Convert internal TransactionRequest to raw TON Connect protocol. */ export function toConnectTransactionParamContent(request: TransactionRequest): RawConnectTransactionParamContent { return { diff --git a/packages/walletkit/src/types/jettons.ts b/packages/walletkit/src/types/jettons.ts index c5a3b4f06..a43d2bcec 100644 --- a/packages/walletkit/src/types/jettons.ts +++ b/packages/walletkit/src/types/jettons.ts @@ -12,22 +12,36 @@ import type { Jetton, Network } from '../api/models'; // === Core Jetton Information === export interface JettonInfo { + /** Jetton master contract address. */ address: string; + /** Display name of the jetton (e.g., `"Tether USD"`). */ name: string; + /** Ticker symbol (e.g., `"USDT"`). */ symbol: string; + /** Free-form description set by the issuer. */ description: string; + /** Number of decimal places used to format raw amounts (e.g., `6` for USDT). */ decimals?: number; + /** Total supply in raw smallest units. */ totalSupply?: string; + /** URL of the jetton's image. */ image?: string; + /** Inline image data (Base64) when no `image` URL is published. */ image_data?: string; + /** Off-chain metadata URI (TEP-64). */ uri?: string; + /** Verification status reported by the indexer. */ verification?: JettonVerification; + /** Additional indexer-supplied metadata that doesn't fit the canonical fields. */ metadata?: Record; } export interface JettonVerification { + /** `true` when the indexer has verified this jetton against an allow-list. */ verified: boolean; + /** Origin of the verification claim. */ source?: 'toncenter' | 'community' | 'manual'; + /** Free-form warnings the UI should surface (e.g., scam indicators). */ warnings?: string[]; } @@ -161,6 +175,6 @@ export interface JettonsAPI { getAddressJettons(userAddress: string, network: Network, offset?: number, limit?: number): Promise; // === Validation === - /** Validate jetton address format */ + /** Validate jetton address format. */ validateJettonAddress(address: string): boolean; } diff --git a/packages/walletkit/src/types/jsBridge.ts b/packages/walletkit/src/types/jsBridge.ts index 20515b2d8..c9b1e35d8 100644 --- a/packages/walletkit/src/types/jsBridge.ts +++ b/packages/walletkit/src/types/jsBridge.ts @@ -90,7 +90,7 @@ export interface TonConnectBridge { } /** - * Options for JS Bridge injection + * Options for JS Bridge injection. */ export interface JSBridgeInjectOptions { deviceInfo?: Partial; @@ -101,7 +101,7 @@ export interface JSBridgeInjectOptions { } /** - * Internal message types for communication between injected bridge and extension + * Internal message types for communication between injected bridge and extension. */ export interface InjectedToExtensionBridgeRequest { type: typeof TONCONNECT_BRIDGE_REQUEST; diff --git a/packages/walletkit/src/types/kit.ts b/packages/walletkit/src/types/kit.ts index 878fe718f..fcc77ed7c 100644 --- a/packages/walletkit/src/types/kit.ts +++ b/packages/walletkit/src/types/kit.ts @@ -45,35 +45,35 @@ export interface ITonWalletKit { */ getApiClient(network: Network): ApiClient; - /** Network manager for all configured API clients */ + /** Network manager for all configured API clients. */ getNetworkManager(): NetworkManager; - /** Get all configured networks */ + /** Get all configured networks. */ getConfiguredNetworks(): Network[]; - /** Get factory context */ + /** Get factory context. */ createFactoryContext(): ProviderFactoryContext; isReady(): boolean; - /** Ensure initialization is complete */ + /** Ensure initialization is complete. */ ensureInitialized(): Promise; // === Wallet Management === - /** Get all registered wallets */ + /** Get all registered wallets. */ getWallets(): Wallet[]; /** Get wallet by wallet ID (network:address format) */ getWallet(walletId: WalletId): Wallet | undefined; - /** Add a new wallet, returns wallet ID */ + /** Add a new wallet, returns wallet ID. */ addWallet(adapter: WalletAdapter): Promise; - /** Remove a wallet by wallet ID or adapter */ + /** Remove a wallet by wallet ID or adapter. */ removeWallet(walletIdOrAdapter: WalletId | WalletAdapter): Promise; - /** Clear all wallets */ + /** Clear all wallets. */ clearWallets(): Promise; // === Session Management === @@ -81,89 +81,89 @@ export interface ITonWalletKit { /** Disconnect session(s) */ disconnect(sessionId?: string): Promise; - /** List all active sessions */ + /** List all active sessions. */ listSessions(): Promise; // === URL Parsing API === /** - * Allow to convert url to ConnectionRequestEvent to use inline way + * Allow to convert url to ConnectionRequestEvent to use inline way. */ connectionEventFromUrl(url: string): Promise; // === URL Processing === - /** Handle pasted TON Connect URL/link */ + /** Handle pasted TON Connect URL/link. */ handleTonConnectUrl(url: string): Promise; - /** Handle new transaction */ + /** Handle new transaction. */ handleNewTransaction(wallet: Wallet, data: TransactionRequest): Promise; // === Request Processing === - /** Approve a connect request */ + /** Approve a connect request. */ approveConnectRequest(event: ConnectionRequestEvent, response?: ConnectionApprovalResponse): Promise; - /** Reject a connect request */ + /** Reject a connect request. */ rejectConnectRequest( event: ConnectionRequestEvent, reason?: string, errorCode?: CONNECT_EVENT_ERROR_CODES, ): Promise; - /** Approve a transaction request */ + /** Approve a transaction request. */ approveTransactionRequest( event: SendTransactionRequestEvent, response?: SendTransactionApprovalResponse, ): Promise; - /** Reject a transaction request */ + /** Reject a transaction request. */ rejectTransactionRequest( event: SendTransactionRequestEvent, reason?: string | SendTransactionRpcResponseError['error'], ): Promise; - /** Approve a sign data request */ + /** Approve a sign data request. */ approveSignDataRequest( event: SignDataRequestEvent, response?: SignDataApprovalResponse, ): Promise; - /** Reject a sign data request */ + /** Reject a sign data request. */ rejectSignDataRequest(event: SignDataRequestEvent, reason?: string): Promise; // === Event Handlers === - /** Register connect request handler */ + /** Register connect request handler. */ onConnectRequest(cb: (event: ConnectionRequestEvent) => void): void; - /** Register transaction request handler */ + /** Register transaction request handler. */ onTransactionRequest(cb: (event: SendTransactionRequestEvent) => void): void; - /** Register sign data request handler */ + /** Register sign data request handler. */ onSignDataRequest(cb: (event: SignDataRequestEvent) => void): void; - /** Register disconnect handler */ + /** Register disconnect handler. */ onDisconnect(cb: (event: DisconnectionEvent) => void): void; - /** Register error handler */ + /** Register error handler. */ onRequestError(cb: (event: RequestErrorEvent) => void): void; - /** Remove request handlers */ + /** Remove request handlers. */ removeConnectRequestCallback(cb: (event: ConnectionRequestEvent) => void): void; removeTransactionRequestCallback(cb: (event: SendTransactionRequestEvent) => void): void; removeSignDataRequestCallback(cb: (event: SignDataRequestEvent) => void): void; removeDisconnectCallback(cb: (event: DisconnectionEvent) => void): void; removeErrorCallback(cb: (event: RequestErrorEvent) => void): void; - /** Jettons API access */ + /** Jettons API access. */ jettons: JettonsAPI; - /** Jettons API access */ + /** Jettons API access. */ swap: SwapAPI; - /** Get streaming manager */ + /** Get streaming manager. */ streaming: StreamingAPI; - /** Staking API access */ + /** Staking API access. */ staking: StakingAPI; } diff --git a/packages/walletkit/src/types/toncenter/AccountEvent.ts b/packages/walletkit/src/types/toncenter/AccountEvent.ts index a01079c98..140d47c93 100644 --- a/packages/walletkit/src/types/toncenter/AccountEvent.ts +++ b/packages/walletkit/src/types/toncenter/AccountEvent.ts @@ -117,7 +117,7 @@ export function toAddressBook(data: MetadataV3): AddressBook { export interface Event { eventId: Hex; - /** Normalized trace external hash (base64url) for deduplication with WebSocket pending */ + /** Normalized trace external hash (base64url) for deduplication with WebSocket pending. */ traceExternalHash?: string; account: Account; timestamp: number; @@ -223,7 +223,7 @@ export type Action = | JettonSwapAction; /** - * Helper: Build Event structure from parsed data + * Helper: Build Event structure from parsed data. */ function buildEvent(data: ToncenterTraceItem, account: string, actions: Action[], addressBook: AddressBook): Event { // Prefer hash_norm (TEP-467 normalized) to match WebSocket trace_external_hash_norm; fallback to raw hash @@ -270,7 +270,7 @@ function filterActionsByPriority(actions: Action[]): Action[] { } /** - * Parse trace item into structured Event with typed actions + * Parse trace item into structured Event with typed actions. */ export function toEvent(data: ToncenterTraceItem, account: string, addressBook: AddressBook = {}): Event { const accountFriendly = asAddressFriendly(account); diff --git a/packages/walletkit/src/types/toncenter/ApiClient.ts b/packages/walletkit/src/types/toncenter/ApiClient.ts index e0ad6d43a..4aa93a5a7 100644 --- a/packages/walletkit/src/types/toncenter/ApiClient.ts +++ b/packages/walletkit/src/types/toncenter/ApiClient.ts @@ -95,34 +95,52 @@ export interface GetEventsResponse { } export interface ApiClient { + /** Look up specific NFT items by address. */ nftItemsByAddress(request: NFTsRequest): Promise; + /** List NFT items held by an owner. Supports pagination. */ nftItemsByOwner(request: UserNFTsRequest): Promise; + /** Run an emulation pass on a Base64-encoded BoC. Returns the predicted account-state changes and emitted events without sending the message. */ fetchEmulation(messageBoc: Base64String, ignoreSignature?: boolean): Promise; + /** Broadcast a signed BoC to the network and return the message hash. */ sendBoc(boc: Base64String): Promise; + /** Run an on-chain `get` method against a contract and read its TVM stack output. */ runGetMethod( address: UserFriendlyAddress, method: string, stack?: RawStackItem[], seqno?: number, ): Promise; // TODO - Make serializable + /** Read the full on-chain account state (code, data, status, balance) for an address. */ getAccountState(address: UserFriendlyAddress, seqno?: number): Promise; + /** Read the TON balance of an address in raw nanotons. */ getBalance(address: UserFriendlyAddress, seqno?: number): Promise; + /** List transactions for an address. Ordered newest-first, paginated via `LimitRequest`. */ getAccountTransactions(request: TransactionsByAddressRequest): Promise; + /** Fetch a transaction by its message or body hash. */ getTransactionsByHash(request: GetTransactionByHashRequest): Promise; + /** List pending (unconfirmed) transactions by accounts or trace ids. Useful for "in-flight" UIs. */ getPendingTransactions(request: GetPendingTransactionsRequest): Promise; + /** Fetch a confirmed trace (the tree of internal messages spawned by an external one). */ getTrace(request: GetTraceRequest): Promise; + /** Fetch a pending trace by external-message hash, while it's still in flight. */ getPendingTrace(request: GetPendingTraceRequest): Promise; + /** Resolve a TON DNS domain to the wallet address it points at. `null` when unset. */ resolveDnsWallet(domain: string): Promise; + /** Reverse-resolve a wallet address to a TON DNS domain that points at it. `null` when none. */ backResolveDnsWallet(address: UserFriendlyAddress): Promise; + /** Look up jetton masters by address — returns indexer metadata for the requested jettons. */ jettonsByAddress(request: GetJettonsByAddressRequest): Promise; + /** List jetton holdings owned by an address — returns balances + jetton-master metadata. */ jettonsByOwnerAddress(request: GetJettonsByOwnerRequest): Promise; + /** List parsed account events (jetton transfers, NFT moves, swaps, …) for an address. */ getEvents(request: GetEventsRequest): Promise; + /** Read the latest masterchain info — last seqno, shards, time. */ getMasterchainInfo(): Promise; } diff --git a/packages/walletkit/src/types/toncenter/parsers/body.ts b/packages/walletkit/src/types/toncenter/parsers/body.ts index e97dea2fc..febd713d9 100644 --- a/packages/walletkit/src/types/toncenter/parsers/body.ts +++ b/packages/walletkit/src/types/toncenter/parsers/body.ts @@ -8,7 +8,7 @@ /** * Common helpers for extracting decoded body and operation types from messages - * Refactored to use centralized opcode registry and message decoder + * Refactored to use centralized opcode registry and message decoder. */ import type { EmulationMessage } from '../emulation'; @@ -35,7 +35,7 @@ export function extractOpFromBody(msg?: EmulationMessage | null): string | null /** * Match operation code with type mapping - * Now uses centralized opcode registry + * Now uses centralized opcode registry. */ export function matchOpWithMap(op: string, types: string[], mapping: Record): string | '' { if (!op) return ''; @@ -55,7 +55,7 @@ export function matchOpWithMap(op: string, types: string[], mapping: Record { messageType: MessageType; @@ -26,7 +26,7 @@ export interface DecodedMessage { } /** - * Pattern matcher for message types + * Pattern matcher for message types. */ export interface MessagePattern { messageType: MessageType; @@ -35,18 +35,18 @@ export interface MessagePattern { } /** - * Generic decoded payload type + * Generic decoded payload type. */ export type DecodedPayload = Record; /** - * Registry of message patterns + * Registry of message patterns. */ class MessagePatternRegistry { private patterns: Map = new Map(); /** - * Register a pattern for a message type + * Register a pattern for a message type. */ register(pattern: MessagePattern): void { const existing = this.patterns.get(pattern.messageType) || []; @@ -55,7 +55,7 @@ class MessagePatternRegistry { } /** - * Find matching pattern for a message + * Find matching pattern for a message. */ match(msg: EmulationMessage): MessagePattern | null { for (const patterns of this.patterns.values()) { @@ -69,7 +69,7 @@ class MessagePatternRegistry { } /** - * Get all patterns for a message type + * Get all patterns for a message type. */ getPatterns(messageType: MessageType): MessagePattern[] { return this.patterns.get(messageType) || []; @@ -77,12 +77,12 @@ class MessagePatternRegistry { } /** - * Global pattern registry + * Global pattern registry. */ export const messagePatternRegistry = new MessagePatternRegistry(); /** - * Extracts decoded body from message + * Extracts decoded body from message. */ export function getDecodedBody(msg?: EmulationMessage | null): DecodedPayload | null { if (!msg) return null; @@ -95,7 +95,7 @@ export function getDecodedBody(msg?: EmulationMessage | null): DecodedPayload | } /** - * Extracts @type from decoded body + * Extracts @type from decoded body. */ export function getDecodedType(msg?: EmulationMessage | null): string | null { const decoded = getDecodedBody(msg); @@ -112,7 +112,7 @@ export function getDecodedType(msg?: EmulationMessage | null): string | null { } /** - * Decodes a message using pattern matching + * Decodes a message using pattern matching. */ export function decodeMessage(msg: EmulationMessage): DecodedMessage | null { // Try pattern matching first @@ -163,28 +163,28 @@ export function decodeMessage(msg: EmulationMessage): DecodedMessage | null { } /** - * Decodes multiple messages + * Decodes multiple messages. */ export function decodeMessages(messages: EmulationMessage[]): DecodedMessage[] { return messages.map(decodeMessage).filter((m): m is DecodedMessage => m !== null); } /** - * Helper: check if value is a record + * Helper: check if value is a record. */ function isRecord(v: unknown): v is Record { return typeof v === 'object' && v !== null; } /** - * Helper: extract property from decoded payload + * Helper: extract property from decoded payload. */ export function getPayloadProperty(payload: DecodedPayload, key: string): T | undefined { return payload[key] as T | undefined; } /** - * Helper: extract nested property from decoded payload + * Helper: extract nested property from decoded payload. */ export function getNestedProperty(payload: DecodedPayload, path: string[]): T | undefined { let current: unknown = payload; diff --git a/packages/walletkit/src/types/toncenter/parsers/messageHandler.ts b/packages/walletkit/src/types/toncenter/parsers/messageHandler.ts index 21f2ff254..8ff09da58 100644 --- a/packages/walletkit/src/types/toncenter/parsers/messageHandler.ts +++ b/packages/walletkit/src/types/toncenter/parsers/messageHandler.ts @@ -8,7 +8,7 @@ /** * Extensible message handler architecture - * Allows registration of custom handlers for different message types + * Allows registration of custom handlers for different message types. */ import type { MessageType } from './opcodes'; @@ -17,7 +17,7 @@ import type { Action, AddressBook } from '../AccountEvent'; import type { ToncenterTraceItem, ToncenterTransaction } from '../emulation'; /** - * Context for message handling + * Context for message handling. */ export interface MessageHandlerContext { ownerAddress: string; @@ -27,11 +27,11 @@ export interface MessageHandlerContext { } /** - * Message handler interface + * Message handler interface. */ export interface MessageHandler { /** - * Message type this handler processes + * Message type this handler processes. */ messageType: MessageType; @@ -41,24 +41,24 @@ export interface MessageHandler { priority?: number; /** - * Check if this handler can process the message + * Check if this handler can process the message. */ canHandle(message: DecodedMessage, context: MessageHandlerContext): boolean; /** - * Process the message and return actions + * Process the message and return actions. */ handle(message: DecodedMessage, context: MessageHandlerContext): Action[]; } /** - * Message handler registry + * Message handler registry. */ class MessageHandlerRegistry { private handlers: Map = new Map(); /** - * Register a message handler + * Register a message handler. */ register(handler: MessageHandler): void { const existing = this.handlers.get(handler.messageType) || []; @@ -69,7 +69,7 @@ class MessageHandlerRegistry { } /** - * Unregister a handler + * Unregister a handler. */ unregister(handler: MessageHandler): void { const existing = this.handlers.get(handler.messageType); @@ -80,14 +80,14 @@ class MessageHandlerRegistry { } /** - * Get all handlers for a message type + * Get all handlers for a message type. */ getHandlers(messageType: MessageType): MessageHandler[] { return this.handlers.get(messageType) || []; } /** - * Find the first handler that can handle the message + * Find the first handler that can handle the message. */ findHandler(message: DecodedMessage, context: MessageHandlerContext): MessageHandler | null { const handlers = this.getHandlers(message.messageType); @@ -100,7 +100,7 @@ class MessageHandlerRegistry { } /** - * Process a message with the appropriate handler + * Process a message with the appropriate handler. */ handle(message: DecodedMessage, context: MessageHandlerContext): Action[] { const handler = this.findHandler(message, context); @@ -111,14 +111,14 @@ class MessageHandlerRegistry { } /** - * Get all registered message types + * Get all registered message types. */ getRegisteredTypes(): MessageType[] { return Array.from(this.handlers.keys()); } /** - * Clear all handlers + * Clear all handlers. */ clear(): void { this.handlers.clear(); @@ -126,12 +126,12 @@ class MessageHandlerRegistry { } /** - * Global message handler registry + * Global message handler registry. */ export const messageHandlerRegistry = new MessageHandlerRegistry(); /** - * Base message handler with common utilities + * Base message handler with common utilities. */ export abstract class BaseMessageHandler implements MessageHandler { abstract messageType: MessageType; @@ -141,14 +141,14 @@ export abstract class BaseMessageHandler implements MessageHandler { abstract handle(message: DecodedMessage, context: MessageHandlerContext): Action[]; /** - * Helper: check if value is a record + * Helper: check if value is a record. */ protected isRecord(v: unknown): v is Record { return typeof v === 'object' && v !== null; } /** - * Helper: get property from payload + * Helper: get property from payload. */ protected getProperty(payload: unknown, key: string): T | undefined { if (this.isRecord(payload)) { @@ -158,7 +158,7 @@ export abstract class BaseMessageHandler implements MessageHandler { } /** - * Helper: safely convert to bigint + * Helper: safely convert to bigint. */ protected toBigInt(value?: string | number): bigint { if (value === undefined || value === null) return BigInt(0); @@ -167,7 +167,7 @@ export abstract class BaseMessageHandler implements MessageHandler { } /** - * Helper: extract comment from decoded payload + * Helper: extract comment from decoded payload. */ protected extractComment(payload: unknown): string | null { if (!this.isRecord(payload)) return null; @@ -183,7 +183,7 @@ export abstract class BaseMessageHandler implements MessageHandler { } /** - * Decorator for registering handlers automatically + * Decorator for registering handlers automatically. */ export function RegisterMessageHandler(messageType: MessageType, priority?: number) { return function (constructor: T): T { @@ -199,7 +199,7 @@ export function RegisterMessageHandler(messageType: MessageType, priority?: numb } /** - * Fluent builder for creating handlers + * Fluent builder for creating handlers. */ export class MessageHandlerBuilder { private _messageType?: MessageType; @@ -259,7 +259,7 @@ export class MessageHandlerBuilder { } /** - * Create a new message handler builder + * Create a new message handler builder. */ export function createMessageHandler(): MessageHandlerBuilder { return new MessageHandlerBuilder(); diff --git a/packages/walletkit/src/types/toncenter/parsers/opcodes.ts b/packages/walletkit/src/types/toncenter/parsers/opcodes.ts index 705fe54a0..2c65dd726 100644 --- a/packages/walletkit/src/types/toncenter/parsers/opcodes.ts +++ b/packages/walletkit/src/types/toncenter/parsers/opcodes.ts @@ -8,7 +8,7 @@ /** * Registry of known operation codes for TON blockchain messages - * Provides type-safe opcode definitions and utilities for matching messages + * Provides type-safe opcode definitions and utilities for matching messages. */ export enum OpCode { @@ -42,7 +42,7 @@ export enum OpCode { } /** - * Message type names corresponding to opcodes + * Message type names corresponding to opcodes. */ export enum MessageType { JettonTransfer = 'jetton_transfer', @@ -65,7 +65,7 @@ export enum MessageType { } /** - * Bidirectional mapping between opcodes and message types + * Bidirectional mapping between opcodes and message types. */ export const OpCodeMapping: Record = { [OpCode.JettonTransfer]: MessageType.JettonTransfer, @@ -90,7 +90,7 @@ export const OpCodeMapping: Record = { }; /** - * Reverse mapping for quick lookup + * Reverse mapping for quick lookup. */ export const MessageTypeToOpCode: Record = { [MessageType.JettonTransfer]: OpCode.JettonTransfer, @@ -112,7 +112,7 @@ export const MessageTypeToOpCode: Record = { }; /** - * Legacy mapping for backwards compatibility + * Legacy mapping for backwards compatibility. */ export const LegacyOpCodeMap: Record = { '0x0f8a7ea5': 'jetton_transfer', @@ -126,7 +126,7 @@ export const LegacyOpCodeMap: Record = { }; /** - * Resolves an opcode string to a MessageType + * Resolves an opcode string to a MessageType. */ export function resolveOpCode(opcode: string): MessageType { const normalized = opcode.toLowerCase(); @@ -148,7 +148,7 @@ export function resolveOpCode(opcode: string): MessageType { } /** - * Checks if an opcode matches any of the given message types + * Checks if an opcode matches any of the given message types. */ export function matchesMessageType(opcode: string, types: MessageType[]): MessageType | null { const resolved = resolveOpCode(opcode); @@ -156,7 +156,7 @@ export function matchesMessageType(opcode: string, types: MessageType[]): Messag } /** - * Checks if decoded message matches a message type + * Checks if decoded message matches a message type. */ export function matchesDecodedType(decodedType: string, types: MessageType[]): MessageType | null { // Try direct match with decoded @type diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 17e9def08..e82ebbd46 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -517,7 +517,72 @@ importers: specifier: 5.9.3 version: 5.9.3 - demo/examples: + demo/v4ledger-adapter: + dependencies: + '@ledgerhq/hw-transport': + specifier: 6.32.0 + version: 6.32.0 + '@ton-community/ton-ledger': + specifier: ^7.3.0 + version: 7.3.0(@ton/core@0.63.1(@ton/crypto@3.3.0)) + '@ton/core': + specifier: 'catalog:' + version: 0.63.1(@ton/crypto@3.3.0) + '@ton/walletkit': + specifier: workspace:* + version: link:../../packages/walletkit + '@tonconnect/protocol': + specifier: 'catalog:' + version: 2.4.0 + devDependencies: + '@ledgerhq/hw-transport-node-hid': + specifier: 6.30.0 + version: 6.30.0 + dotenv: + specifier: ^17.4.2 + version: 17.4.2 + rimraf: + specifier: ^6.1.2 + version: 6.1.3 + typescript: + specifier: ~5.9.3 + version: 5.9.3 + + demo/wallet-core: + dependencies: + '@demo/v4ledger-adapter': + specifier: workspace:* + version: link:../v4ledger-adapter + '@ton/core': + specifier: 'catalog:' + version: 0.63.1(@ton/crypto@3.3.0) + '@ton/crypto': + specifier: 'catalog:' + version: 3.3.0 + '@ton/walletkit': + specifier: workspace:* + version: link:../../packages/walletkit + immer: + specifier: ^10.2.0 + version: 10.2.0 + react: + specifier: 'catalog:' + version: 19.2.3 + zustand: + specifier: ^5.0.8 + version: 5.0.10(@types/react@19.2.14)(immer@10.2.0)(react@19.2.3)(use-sync-external-store@1.6.0(react@19.2.3)) + devDependencies: + '@types/react': + specifier: 'catalog:' + version: 19.2.14 + rimraf: + specifier: ^6.1.2 + version: 6.1.3 + typescript: + specifier: ~5.9.3 + version: 5.9.3 + + docs/examples: dependencies: '@tanstack/react-query': specifier: 'catalog:' @@ -572,67 +637,31 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@25.6.0)(@vitest/coverage-v8@4.1.4)(@vitest/ui@4.1.4)(happy-dom@20.8.9)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.3)) - demo/v4ledger-adapter: + docs/reference-generator: dependencies: - '@ledgerhq/hw-transport': - specifier: 6.32.0 - version: 6.32.0 - '@ton-community/ton-ledger': - specifier: ^7.3.0 - version: 7.3.0(@ton/core@0.63.1(@ton/crypto@3.3.0)) - '@ton/core': - specifier: 'catalog:' - version: 0.63.1(@ton/crypto@3.3.0) - '@ton/walletkit': - specifier: workspace:* - version: link:../../packages/walletkit - '@tonconnect/protocol': - specifier: 'catalog:' - version: 2.4.0 + ts-morph: + specifier: ^28.0.0 + version: 28.0.0 devDependencies: - '@ledgerhq/hw-transport-node-hid': - specifier: 6.30.0 - version: 6.30.0 - dotenv: - specifier: ^17.4.2 - version: 17.4.2 - rimraf: - specifier: ^6.1.2 - version: 6.1.3 + tsx: + specifier: ^4.21.0 + version: 4.21.0 typescript: specifier: ~5.9.3 version: 5.9.3 - demo/wallet-core: + docs/template-resolver: dependencies: - '@demo/v4ledger-adapter': - specifier: workspace:* - version: link:../v4ledger-adapter - '@ton/core': - specifier: 'catalog:' - version: 0.63.1(@ton/crypto@3.3.0) - '@ton/crypto': - specifier: 'catalog:' - version: 3.3.0 - '@ton/walletkit': - specifier: workspace:* - version: link:../../packages/walletkit - immer: - specifier: ^10.2.0 - version: 10.2.0 - react: - specifier: 'catalog:' - version: 19.2.3 - zustand: - specifier: ^5.0.8 - version: 5.0.10(@types/react@19.2.14)(immer@10.2.0)(react@19.2.3)(use-sync-external-store@1.6.0(react@19.2.3)) + eslint: + specifier: ^9.39.4 + version: 9.39.4(jiti@2.6.1) + prettier: + specifier: ^3.6.2 + version: 3.8.1 devDependencies: - '@types/react': - specifier: 'catalog:' - version: 19.2.14 - rimraf: - specifier: ^6.1.2 - version: 6.1.3 + tsx: + specifier: ^4.21.0 + version: 4.21.0 typescript: specifier: ~5.9.3 version: 5.9.3 @@ -4072,6 +4101,9 @@ packages: '@truecarry/webext-bridge@6.0.2': resolution: {integrity: sha512-Q2gmBkfbForHKxvDKI2Ep5LGih7+wEsjluXqNxUHNXW2b8ztNmuI77nZBqNLb83B3AeKGxe0txPnCycPVgYzXA==} + '@ts-morph/common@0.29.0': + resolution: {integrity: sha512-35oUmphHbJvQ/+UTwFNme/t2p3FoKiGJ5auTjjpNTop2dyREspirjMy82PLSC1pnDJ8ah1GU98hwpVt64YXQsg==} + '@tsconfig/node10@1.0.12': resolution: {integrity: sha512-UCYBaeFvM11aU2y3YPZ//O5Rhj+xKyzy7mvcIoAjASbigy8mHMryP5cK7dgjlz2hWxh1g5pLw084E0a/wlUSFQ==} @@ -5196,6 +5228,9 @@ packages: resolution: {integrity: sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==} engines: {iojs: '>= 1.0.0', node: '>= 0.12.0'} + code-block-writer@13.0.3: + resolution: {integrity: sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg==} + collect-v8-coverage@1.0.3: resolution: {integrity: sha512-1L5aqIkwPfiodaMgQunkF1zRhNqifHBmtbbbxcr6yVxxBnliw4TDOW6NxpO8DJLgJ16OT+Y4ztZqP6p/FtXnAw==} @@ -9394,6 +9429,9 @@ packages: engines: {node: '>=22.0.0'} hasBin: true + ts-morph@28.0.0: + resolution: {integrity: sha512-Wp3tnZ2bzwxyTZMtgWVzXDfm7lB1Drz+y9DmmYH/L702PQhPyVrp3pkou3yIz4qjS14GY9kcpmLiOOMvl8oG1g==} + ts-node@10.9.2: resolution: {integrity: sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==} hasBin: true @@ -9673,14 +9711,17 @@ packages: uuid@7.0.3: resolution: {integrity: sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==} + deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028). hasBin: true uuid@8.3.2: resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==} + deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028). hasBin: true uuid@9.0.1: resolution: {integrity: sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==} + deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028). hasBin: true v8-compile-cache-lib@3.0.1: @@ -13891,7 +13932,7 @@ snapshots: '@testing-library/dom@10.4.1': dependencies: '@babel/code-frame': 7.29.0 - '@babel/runtime': 7.28.6 + '@babel/runtime': 7.29.2 '@types/aria-query': 5.0.4 aria-query: 5.3.0 dom-accessibility-api: 0.5.16 @@ -13920,7 +13961,7 @@ snapshots: '@testing-library/react@16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)': dependencies: - '@babel/runtime': 7.28.6 + '@babel/runtime': 7.29.2 '@testing-library/dom': 10.4.1 react: 19.2.3 react-dom: 19.2.3(react@19.2.3) @@ -14085,6 +14126,12 @@ snapshots: tiny-uid: 1.1.2 webextension-polyfill: 0.9.0 + '@ts-morph/common@0.29.0': + dependencies: + minimatch: 10.2.5 + path-browserify: 1.0.1 + tinyglobby: 0.2.16 + '@tsconfig/node10@1.0.12': {} '@tsconfig/node12@1.0.11': {} @@ -15434,6 +15481,8 @@ snapshots: co@4.6.0: {} + code-block-writer@13.0.3: {} + collect-v8-coverage@1.0.3: {} color-convert@1.9.3: @@ -18084,7 +18133,7 @@ snapshots: metro-runtime@0.83.3: dependencies: - '@babel/runtime': 7.28.6 + '@babel/runtime': 7.29.2 flow-enums-runtime: 0.0.6 metro-runtime@0.83.5: @@ -20368,8 +20417,8 @@ snapshots: tinyglobby@0.2.15: dependencies: - fdir: 6.5.0(picomatch@4.0.3) - picomatch: 4.0.3 + fdir: 6.5.0(picomatch@4.0.4) + picomatch: 4.0.4 tinyglobby@0.2.16: dependencies: @@ -20460,6 +20509,11 @@ snapshots: tslib: 2.8.1 typescript: 5.9.3 + ts-morph@28.0.0: + dependencies: + '@ts-morph/common': 0.29.0 + code-block-writer: 13.0.3 + ts-node@10.9.2(@types/node@25.6.0)(typescript@5.9.3): dependencies: '@cspotcode/source-map-support': 0.8.1 @@ -20495,7 +20549,7 @@ snapshots: tsx@4.21.0: dependencies: - esbuild: 0.27.3 + esbuild: 0.27.7 get-tsconfig: 4.13.6 optionalDependencies: fsevents: 2.3.3 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 582e16182..dac148b37 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -2,6 +2,7 @@ packages: - packages/* - apps/* - demo/* + - docs/* catalog: '@tanstack/query-core': 5.99.0 From 4f537518534886984d351cf524200551b19c0dde Mon Sep 17 00:00:00 2001 From: VK Date: Thu, 14 May 2026 18:21:57 +0400 Subject: [PATCH 2/2] docs(appkit): add dots + fix decimals --- .../packages/appkit-react/docs/reference.md | 52 +-- .../packages/appkit/docs/reference.md | 420 +++++++++--------- packages/appkit-react/docs/reference.md | 52 +-- packages/appkit/docs/reference.md | 420 +++++++++--------- 4 files changed, 472 insertions(+), 472 deletions(-) diff --git a/docs/templates/packages/appkit-react/docs/reference.md b/docs/templates/packages/appkit-react/docs/reference.md index 182ddd622..e24ac70cf 100644 --- a/docs/templates/packages/appkit-react/docs/reference.md +++ b/docs/templates/packages/appkit-react/docs/reference.md @@ -138,10 +138,10 @@ Quote a crypto-to-TON onramp — given a source asset/chain and the target TON a | `parameters.sourceCurrencyAddress` | `string` | Source crypto currency address (contract address or 0x0... for native) | | `parameters.sourceChain` | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | | `parameters.targetCurrencyAddress` | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | -| `parameters.recipientAddress` | `string` | TON address that will receive the target crypto | -| `parameters.refundAddress` | `string` | Refund address for the source crypto | +| `parameters.recipientAddress` | `string` | TON address that will receive the target crypto. | +| `parameters.refundAddress` | `string` | Refund address for the source crypto. | | `parameters.isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | -| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `parameters.providerId` | `string` | Provider to quote against. Defaults to the registered default provider. | | `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | @@ -154,8 +154,8 @@ Read the current status of a crypto-onramp deposit previously created via [`useC | Parameter | Type | Description | | --- | --- | --- | | `parameters` | [`UseCryptoOnrampStatusParameters`](#usecryptoonrampstatusparameters) | Deposit id, originating provider id and TanStack Query overrides. | -| `parameters.depositId` | `string` | Deposit id | -| `parameters.providerId` | `string` | Identifier of the provider that issued this deposit | +| `parameters.depositId` | `string` | Deposit id. | +| `parameters.providerId` | `string` | Identifier of the provider that issued this deposit. | | `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | Returns: UseCryptoOnrampStatusReturnType<selectData = GetCryptoOnrampStatusData> — TanStack Query result for the status read. @@ -539,12 +539,12 @@ Quote a stake or unstake — given an amount, direction (`'stake'` / `'unstake'` | --- | --- | --- | | `parameters` | [`UseStakingQuoteParameters`](#usestakingquoteparameters) | Quote parameters, optional `providerId`, optional network override, and TanStack Query overrides. | | `parameters.direction` | StakingQuoteDirection | Direction of the quote (stake or unstake) | -| `parameters.amount` | `string` | Amount of tokens to stake or unstake | -| `parameters.userAddress` | UserFriendlyAddress | Address of the user | -| `parameters.network` | Network | Network on which the staking will be executed | +| `parameters.amount` | `string` | Amount of tokens to stake or unstake. | +| `parameters.userAddress` | UserFriendlyAddress | Address of the user. | +| `parameters.network` | Network | Network on which the staking will be executed. | | `parameters.unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](/ecosystem/appkit/reference/appkit#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | | `parameters.isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | -| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `parameters.providerId` | `string` | Provider to quote against. Defaults to the registered default staking provider. | | `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | @@ -589,12 +589,12 @@ Quote a swap — given source/target tokens and an amount, returns the rate, exp | --- | --- | --- | | `parameters` | [`UseSwapQuoteParameters`](#useswapquoteparameters) | Source and target tokens, amount, optional network/provider override, and TanStack Query overrides. | | `parameters.amount` | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | -| `parameters.from` | SwapToken | Token to swap from | -| `parameters.to` | SwapToken | Token to swap to | -| `parameters.network` | Network | Network on which the swap will be executed | +| `parameters.from` | SwapToken | Token to swap from. | +| `parameters.to` | SwapToken | Token to swap to. | +| `parameters.network` | Network | Network on which the swap will be executed. | | `parameters.slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `parameters.maxOutgoingMessages` | `number` | Maximum number of outgoing messages | -| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `parameters.isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | | `parameters.providerId` | `string` | Provider to quote against. Defaults to the registered default swap provider. | | `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | @@ -1872,10 +1872,10 @@ Parameters accepted by [`useCryptoOnrampQuote`](#usecryptoonrampquote) — TanSt | `sourceCurrencyAddress` | `string` | Source crypto currency address (contract address or 0x0... for native) | | `sourceChain` | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | | `targetCurrencyAddress` | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | -| `recipientAddress` | `string` | TON address that will receive the target crypto | -| `refundAddress` | `string` | Refund address for the source crypto | +| `recipientAddress` | `string` | TON address that will receive the target crypto. | +| `refundAddress` | `string` | Refund address for the source crypto. | | `isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `providerId` | `string` | Provider to quote against. Defaults to the registered default provider. | | `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | @@ -1896,8 +1896,8 @@ Parameters accepted by [`useCryptoOnrampStatus`](#usecryptoonrampstatus) — Tan | Field | Type | Description | | --- | --- | --- | -| `depositId` | `string` | Deposit id | -| `providerId` | `string` | Identifier of the provider that issued this deposit | +| `depositId` | `string` | Deposit id. | +| `providerId` | `string` | Identifier of the provider that issued this deposit. | | `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | #### UseCryptoOnrampStatusReturnType @@ -2749,12 +2749,12 @@ Parameters accepted by [`useStakingQuote`](#usestakingquote) — TanStack Query | Field | Type | Description | | --- | --- | --- | | `direction` | StakingQuoteDirection | Direction of the quote (stake or unstake) | -| `amount` | `string` | Amount of tokens to stake or unstake | -| `userAddress` | UserFriendlyAddress | Address of the user | -| `network` | Network | Network on which the staking will be executed | +| `amount` | `string` | Amount of tokens to stake or unstake. | +| `userAddress` | UserFriendlyAddress | Address of the user. | +| `network` | Network | Network on which the staking will be executed. | | `unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](/ecosystem/appkit/reference/appkit#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | | `isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `providerId` | `string` | Provider to quote against. Defaults to the registered default staking provider. | | `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | @@ -2965,12 +2965,12 @@ Parameters accepted by [`useSwapQuote`](#useswapquote) — TanStack Query option | Field | Type | Description | | --- | --- | --- | | `amount` | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | -| `from` | SwapToken | Token to swap from | -| `to` | SwapToken | Token to swap to | -| `network` | Network | Network on which the swap will be executed | +| `from` | SwapToken | Token to swap from. | +| `to` | SwapToken | Token to swap to. | +| `network` | Network | Network on which the swap will be executed. | | `slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `maxOutgoingMessages` | `number` | Maximum number of outgoing messages | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | | `providerId` | `string` | Provider to quote against. Defaults to the registered default swap provider. | | `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | diff --git a/docs/templates/packages/appkit/docs/reference.md b/docs/templates/packages/appkit/docs/reference.md index 414575a0b..8dee6f9a5 100644 --- a/docs/templates/packages/appkit/docs/reference.md +++ b/docs/templates/packages/appkit/docs/reference.md @@ -243,8 +243,8 @@ Create a crypto-onramp deposit from a quote previously obtained via [`getCryptoO | `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | | `options`\* | [`CreateCryptoOnrampDepositOptions`](#createcryptoonrampdepositoptions) | Quote, refund address, and optional provider override. | | `options.quote`\* | CryptoOnrampQuote<TQuoteMetadata = unknown> | Quote to execute the deposit against (contains recipientAddress and provider metadata) | -| `options.refundAddress`\* | `string` | Address to refund the crypto to in case of failure | -| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.refundAddress`\* | `string` | Address to refund the crypto to in case of failure. | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `options.providerId` | `string` | Provider to create the deposit through. Defaults to `quote.providerId`, then to the default provider. | Returns: CreateCryptoOnrampDepositReturnType — Deposit details the UI should show to the user (address, amount, optional `memo`/`expiresAt`). @@ -311,10 +311,10 @@ Quote a crypto-to-TON onramp — given a source asset/chain and target TON asset | `options.sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | | `options.sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | | `options.targetCurrencyAddress`\* | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | -| `options.recipientAddress`\* | `string` | TON address that will receive the target crypto | -| `options.refundAddress` | `string` | Refund address for the source crypto | +| `options.recipientAddress`\* | `string` | TON address that will receive the target crypto. | +| `options.refundAddress` | `string` | Refund address for the source crypto. | | `options.isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | -| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `options.providerId` | `string` | Provider to quote against. Defaults to the registered default provider. | Returns: GetCryptoOnrampQuoteReturnType — Quote with pricing details and the provider metadata required to create a deposit. @@ -327,8 +327,8 @@ Read the current status of a crypto-onramp deposit by id — typically polled un | --- | --- | --- | | `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | | `options`\* | [`GetCryptoOnrampStatusOptions`](#getcryptoonrampstatusoptions) | Deposit id, originating provider id and optional provider override. | -| `options.depositId`\* | `string` | Deposit id | -| `options.providerId`\* | `string` | Identifier of the provider that issued this deposit | +| `options.depositId`\* | `string` | Deposit id. | +| `options.providerId`\* | `string` | Identifier of the provider that issued this deposit. | Returns: GetCryptoOnrampStatusReturnType — Current [`CryptoOnrampStatus`](#cryptoonrampstatus) of the deposit. @@ -802,9 +802,9 @@ Build a [`TransactionRequest`](#transactionrequest) that executes a stake or uns | --- | --- | --- | | `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | | `options`\* | [`BuildStakeTransactionOptions`](#buildstaketransactionoptions) | Quote and optional provider override. | -| `options.quote`\* | StakingQuote | The staking quote based on which the transaction is built | -| `options.userAddress`\* | UserFriendlyAddress | Address of the user performing the staking | -| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.quote`\* | StakingQuote | The staking quote based on which the transaction is built. | +| `options.userAddress`\* | UserFriendlyAddress | Address of the user performing the staking. | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `options.providerId` | `string` | Provider to stake/unstake through. Defaults to the registered default staking provider. | Returns: BuildStakeTransactionReturnType — Transaction request ready to pass to `sendTransaction`. @@ -920,12 +920,12 @@ Quote a stake or unstake — given the amount, direction and target asset, retur | `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | | `options`\* | [`GetStakingQuoteOptions`](#getstakingquoteoptions) | Quote parameters and optional provider override. | | `options.direction`\* | StakingQuoteDirection | Direction of the quote (stake or unstake) | -| `options.amount`\* | `string` | Amount of tokens to stake or unstake | -| `options.userAddress` | UserFriendlyAddress | Address of the user | -| `options.network` | Network | Network on which the staking will be executed | +| `options.amount`\* | `string` | Amount of tokens to stake or unstake. | +| `options.userAddress` | UserFriendlyAddress | Address of the user. | +| `options.network` | Network | Network on which the staking will be executed. | | `options.unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | | `options.isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | -| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `options.providerId` | `string` | Provider to quote against. Defaults to the registered default staking provider. | Returns: GetStakingQuoteReturnType — Quote with pricing details and provider metadata. @@ -968,12 +968,12 @@ Build a [`TransactionRequest`](#transactionrequest) that executes a swap previou | --- | --- | --- | | `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | | `options`\* | [`BuildSwapTransactionOptions`](#buildswaptransactionoptions) | Quote and provider-specific options. | -| `options.quote`\* | SwapQuote | The swap quote based on which the transaction is built | -| `options.userAddress`\* | UserFriendlyAddress | Address of the user performing the swap | +| `options.quote`\* | SwapQuote | The swap quote based on which the transaction is built. | +| `options.userAddress`\* | UserFriendlyAddress | Address of the user performing the swap. | | `options.destinationAddress` | UserFriendlyAddress | Address to receive the swapped tokens (defaults to userAddress) | | `options.slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `options.deadline` | `number` | Unix timestamp (in seconds) after which the swap transaction must not be executed. | -| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | Returns: BuildSwapTransactionReturnType — Transaction request ready to pass to `sendTransaction`. @@ -1054,12 +1054,12 @@ Quote a swap — given source/target tokens and an amount, returns the rate, exp | `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | | `options`\* | [`GetSwapQuoteOptions`](#getswapquoteoptions) | Source and target tokens, amount, optional network and provider override. | | `options.amount`\* | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | -| `options.from`\* | SwapToken | Token to swap from | -| `options.to`\* | SwapToken | Token to swap to | -| `options.network`\* | Network | Network on which the swap will be executed | +| `options.from`\* | SwapToken | Token to swap from. | +| `options.to`\* | SwapToken | Token to swap to. | +| `options.network`\* | Network | Network on which the swap will be executed. | | `options.slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `options.maxOutgoingMessages` | `number` | Maximum number of outgoing messages | -| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `options.isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | | `options.providerId` | `string` | Provider to quote against. Defaults to the registered default swap provider. | @@ -1373,7 +1373,7 @@ Constructor: `new LayerswapCryptoOnrampProvider(config)` | --- | --- | --- | | `config` | LayerswapProviderConfig | Optional [`LayerswapProviderConfig`](#layerswapproviderconfig). Defaults are filled in for any field left undefined. | | `config.apiKey` | `string` | Optional API key. Forwarded as `X-LS-APIKEY` when provided. | -| `config.apiUrl` | `string` | Override the base API URL. Defaults to https://api.layerswap.io/api/v2 | +| `config.apiUrl` | `string` | Override the base API URL. Defaults to https://api.layerswap.io/api/v2. | #### SwapsXyzCryptoOnrampProvider @@ -1385,7 +1385,7 @@ Constructor: `new SwapsXyzCryptoOnrampProvider(config)` | --- | --- | --- | | `config`\* | [`SwapsXyzProviderConfig`](#swapsxyzproviderconfig) | Configuration carrying the required `apiKey` plus optional URL/sender overrides. | | `config.apiKey`\* | `string` | API key issued by swaps.xyz (passed as `x-api-key`) | -| `config.apiUrl` | `string` | Override the base API URL. Defaults to https://api-v2.swaps.xyz/api | +| `config.apiUrl` | `string` | Override the base API URL. Defaults to https://api-v2.swaps.xyz/api. | | `config.defaultSender` | `string` | EVM address used as `sender` on getAction requests. Required by the API even for deposit flows where the actual payer is unknown. Defaults to a null address when omitted. | ### DeFi @@ -1483,8 +1483,8 @@ Constructor: `new DeDustSwapProvider(config)` | `config.maxSplits` | `number` | Maximum number of route splits | | `config.maxLength` | `number` | Maximum route length (hops) | | `config.minPoolUsdTvl` | `string` | Minimum pool TVL in USD | -| `config.metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider | -| `config.referralAddress` | `string` | The address of the referrer | +| `config.metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider. | +| `config.referralAddress` | `string` | The address of the referrer. | | `config.referralFeeBps` | `number` | Referral fee in basis points (max 100 = 1%) | **Example** @@ -1503,11 +1503,11 @@ Constructor: `new OmnistonSwapProvider(config)` | `config.apiUrl` | `string` | Optional URL for the Omniston API | | `config.defaultSlippageBps` | `number` | Default slippage tolerance in basis points (1 bp = 0.01%) | | `config.quoteTimeoutMs` | `number` | Timeout for quote requests in milliseconds | -| `config.providerId` | `string` | Identifier for the provider | -| `config.metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider | -| `config.referrerAddress` | `string` | The address of the referrer | +| `config.providerId` | `string` | Identifier for the provider. | +| `config.metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider. | +| `config.referrerAddress` | `string` | The address of the referrer. | | `config.referrerFeeBps` | `number` | Referrer fee in basis points (1 bp = 0.01%) | -| `config.flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed | +| `config.flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed. | **Example** @@ -1566,11 +1566,11 @@ Update payload delivered to [`watchBalance`](#watchbalance) / [`watchBalanceByAd | Field | Type | Description | | --- | --- | --- | -| `type`\* | `'balance'` | The update type field | -| `address`\* | UserFriendlyAddress | The account address | -| `rawBalance`\* | TokenAmount | The account balance in nano units | -| `balance`\* | `string` | The formatted balance | -| `status`\* | StreamingUpdateStatus | The finality of the update | +| `type`\* | `'balance'` | The update type field. | +| `address`\* | UserFriendlyAddress | The account address. | +| `rawBalance`\* | TokenAmount | The account balance in nano units. | +| `balance`\* | `string` | The formatted balance. | +| `status`\* | StreamingUpdateStatus | Finality stage of the update — see [`StreamingUpdateStatus`](#streamingupdatestatus). | #### GetBalanceByAddressOptions @@ -1666,9 +1666,9 @@ Single entry inside an [`AddressBook`](#addressbook) — pairs the user-friendly | Field | Type | Description | | --- | --- | --- | -| `address` | UserFriendlyAddress | The human-readable representation of the blockchain address | -| `domain` | `string` | The domain name associated with the address if available | -| `interfaces`\* | `string[]` | List of supported interfaces by the address | +| `address` | UserFriendlyAddress | The human-readable representation of the blockchain address. | +| `domain` | `string` | The domain name associated with the address if available. | +| `interfaces`\* | `string[]` | List of supported interfaces by the address. | #### ApiClient @@ -1753,10 +1753,10 @@ Display metadata for a token (TON, jetton, or NFT) — name, symbol, image and a | Field | Type | Description | | --- | --- | --- | -| `name` | `string` | Display name of the token | -| `description` | `string` | Human-readable description of the token | -| `image` | `TokenImage` | Token image in various sizes | -| `animation` | `TokenAnimation` | Animated media associated with the token | +| `name` | `string` | Display name of the token. | +| `description` | `string` | Human-readable description of the token. | +| `image` | `TokenImage` | Token image in various sizes. | +| `animation` | `TokenAnimation` | Animated media associated with the token. | | `symbol` | `string` | Ticker symbol of the token (e.g., "TON", "USDT") | ### Connectors @@ -2070,8 +2070,8 @@ Options for [`createCryptoOnrampDeposit`](#createcryptoonrampdeposit) — extend | Field | Type | Description | | --- | --- | --- | | `quote`\* | CryptoOnrampQuote<TQuoteMetadata = unknown> | Quote to execute the deposit against (contains recipientAddress and provider metadata) | -| `refundAddress`\* | `string` | Address to refund the crypto to in case of failure | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `refundAddress`\* | `string` | Address to refund the crypto to in case of failure. | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `providerId` | `string` | Provider to create the deposit through. Defaults to `quote.providerId`, then to the default provider. | #### CreateCryptoOnrampDepositReturnType @@ -2091,15 +2091,15 @@ to complete the onramp. The provider then delivers the target crypto to the user | Field | Type | Description | | --- | --- | --- | -| `depositId`\* | `string` | Deposit id | -| `address`\* | `string` | Deposit address on the source chain | -| `amount`\* | `string` | Exact amount of source crypto the user must send | +| `depositId`\* | `string` | Deposit id. | +| `address`\* | `string` | Deposit address on the source chain. | +| `amount`\* | `string` | Exact amount of source crypto the user must send. | | `sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | | `sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:42161'). | | `memo` | `string` | Optional memo / tag required by some chains (e.g. XRP, TON comment) | -| `expiresAt` | `number` | Unix timestamp (ms) after which the deposit offer is no longer valid | +| `expiresAt` | `number` | Unix timestamp (ms) after which the deposit offer is no longer valid. | | `chainWarning` | `string` | Chain-specific warning to show the user (e.g. "send only on Solana") | -| `providerId`\* | `string` | Identifier of the provider that issued this deposit | +| `providerId`\* | `string` | Identifier of the provider that issued this deposit. | #### CryptoOnrampDepositParams @@ -2110,8 +2110,8 @@ The recipient is taken from `quote.recipientAddress` set at quote time. | Field | Type | Description | | --- | --- | --- | | `quote`\* | CryptoOnrampQuote<TQuoteMetadata = unknown> | Quote to execute the deposit against (contains recipientAddress and provider metadata) | -| `refundAddress`\* | `string` | Address to refund the crypto to in case of failure | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `refundAddress`\* | `string` | Address to refund the crypto to in case of failure. | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | #### CryptoOnrampProviderInterface @@ -2134,8 +2134,8 @@ Static metadata for a crypto-onramp provider. | Field | Type | Description | | --- | --- | --- | | `name`\* | `string` | Human-readable provider name (e.g. 'Swaps.xyz') | -| `logo` | `string` | URL to the provider's logo image | -| `url` | `string` | URL to the provider's website | +| `logo` | `string` | URL to the provider's logo image. | +| `url` | `string` | URL to the provider's website. | | `isRefundAddressRequired` | `boolean` | Whether this provider requires a refund address on the source chain. When true, the UI must collect a refund address before creating a deposit. | | `isReversedAmountSupported` | `boolean` | Whether this provider supports reversed (target-amount) quotes. When false, the UI should hide the direction toggle and only allow source-amount input. | @@ -2145,24 +2145,24 @@ Used in provider configuration to override fields of the provider's metadata. | Field | Type | Description | | --- | --- | --- | -| `name` | `string` | Override the provider's display name | -| `logo` | `string` | Override the provider's logo URL | -| `url` | `string` | Override the provider's website URL | +| `name` | `string` | Override the provider's display name. | +| `logo` | `string` | Override the provider's logo URL. | +| `url` | `string` | Override the provider's website URL. | #### CryptoOnrampQuote -Crypto onramp quote response with pricing information +Crypto onramp quote response with pricing information. | Field | Type | Description | | --- | --- | --- | | `sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | | `sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:42161'). | | `targetCurrencyAddress`\* | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | -| `sourceAmount`\* | `string` | Amount of source crypto to send | -| `targetAmount`\* | `string` | Amount of target crypto to receive | +| `sourceAmount`\* | `string` | Amount of source crypto to send. | +| `targetAmount`\* | `string` | Amount of target crypto to receive. | | `rate`\* | `string` | Exchange rate (amount of target per 1 unit of source) | -| `recipientAddress`\* | `string` | TON address that will receive the target crypto | -| `providerId`\* | `string` | Identifier of the crypto onramp provider | +| `recipientAddress`\* | `string` | TON address that will receive the target crypto. | +| `providerId`\* | `string` | Identifier of the crypto onramp provider. | | `metadata` | `TMetadata = unknown` | Provider-specific metadata for the quote (e.g. raw response needed to execute) | #### CryptoOnrampQuoteParams @@ -2177,10 +2177,10 @@ The target network is always TON, so only the source side is parameterised. | `sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | | `sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | | `targetCurrencyAddress`\* | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | -| `recipientAddress`\* | `string` | TON address that will receive the target crypto | -| `refundAddress` | `string` | Refund address for the source crypto | +| `recipientAddress`\* | `string` | TON address that will receive the target crypto. | +| `refundAddress` | `string` | Refund address for the source crypto. | | `isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | #### CryptoOnrampStatus @@ -2196,8 +2196,8 @@ Parameters accepted by [`getCryptoOnrampStatus`](#getcryptoonrampstatus) — ide | Field | Type | Description | | --- | --- | --- | -| `depositId`\* | `string` | Deposit id | -| `providerId`\* | `string` | Identifier of the provider that issued this deposit | +| `depositId`\* | `string` | Deposit id. | +| `providerId`\* | `string` | Identifier of the provider that issued this deposit. | #### GetCryptoOnrampProviderOptions @@ -2233,10 +2233,10 @@ Options for [`getCryptoOnrampQuote`](#getcryptoonrampquote) — extends [`Crypto | `sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | | `sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | | `targetCurrencyAddress`\* | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | -| `recipientAddress`\* | `string` | TON address that will receive the target crypto | -| `refundAddress` | `string` | Refund address for the source crypto | +| `recipientAddress`\* | `string` | TON address that will receive the target crypto. | +| `refundAddress` | `string` | Refund address for the source crypto. | | `isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `providerId` | `string` | Provider to quote against. Defaults to the registered default provider. | #### GetCryptoOnrampQuoteReturnType @@ -2253,8 +2253,8 @@ Options for [`getCryptoOnrampStatus`](#getcryptoonrampstatus) — extends [`Cryp | Field | Type | Description | | --- | --- | --- | -| `depositId`\* | `string` | Deposit id | -| `providerId`\* | `string` | Identifier of the provider that issued this deposit | +| `depositId`\* | `string` | Deposit id. | +| `providerId`\* | `string` | Identifier of the provider that issued this deposit. | #### GetCryptoOnrampStatusReturnType @@ -2271,7 +2271,7 @@ Configuration accepted by [`createLayerswapProvider`](#createlayerswapprovider). | Field | Type | Description | | --- | --- | --- | | `apiKey` | `string` | Optional API key. Forwarded as `X-LS-APIKEY` when provided. | -| `apiUrl` | `string` | Override the base API URL. Defaults to https://api.layerswap.io/api/v2 | +| `apiUrl` | `string` | Override the base API URL. Defaults to https://api.layerswap.io/api/v2. | #### LayerswapQuoteMetadata @@ -2291,7 +2291,7 @@ Configuration accepted by [`createSwapsXyzProvider`](#createswapsxyzprovider). | Field | Type | Description | | --- | --- | --- | | `apiKey`\* | `string` | API key issued by swaps.xyz (passed as `x-api-key`) | -| `apiUrl` | `string` | Override the base API URL. Defaults to https://api-v2.swaps.xyz/api | +| `apiUrl` | `string` | Override the base API URL. Defaults to https://api-v2.swaps.xyz/api. | | `defaultSender` | `string` | EVM address used as `sender` on getAction requests. Required by the API even for deposit flows where the actual payer is unknown. Defaults to a null address when omitted. | #### SwapsXyzQuoteMetadata @@ -2507,12 +2507,12 @@ Fungible TEP-74 token held in the user's TON wallet — carries the master contr | --- | --- | --- | | `address`\* | UserFriendlyAddress | The jetton master contract address (the token itself). | | `walletAddress`\* | UserFriendlyAddress | The owner's jetton-wallet contract address — the per-owner contract that actually holds this balance. | -| `balance`\* | TokenAmount | The current jetton balance | -| `info`\* | TokenInfo | Information about the token | +| `balance`\* | TokenAmount | The current jetton balance. | +| `info`\* | TokenInfo | Information about the token. | | `decimalsNumber` | `number` | The number of decimal places used by the token | -| `isVerified`\* | `boolean` | Indicates if the jetton is verified | -| `prices`\* | `JettonPrice[]` | Current prices of the jetton in various currencies | -| `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the jetton | +| `isVerified`\* | `boolean` | Indicates if the jetton is verified. | +| `prices`\* | `JettonPrice[]` | Current prices of the jetton in various currencies. | +| `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the jetton. | #### JettonInfo @@ -2538,14 +2538,14 @@ Update payload delivered to [`watchJettons`](#watchjettons) / [`watchJettonsByAd | Field | Type | Description | | --- | --- | --- | -| `type`\* | `'jettons'` | The update type field | -| `masterAddress`\* | UserFriendlyAddress | The master jetton contract address | -| `walletAddress`\* | UserFriendlyAddress | The jetton wallet contract address | -| `ownerAddress`\* | UserFriendlyAddress | The owner of the jetton wallet | +| `type`\* | `'jettons'` | The update type field. | +| `masterAddress`\* | UserFriendlyAddress | The master jetton contract address. | +| `walletAddress`\* | UserFriendlyAddress | The jetton wallet contract address. | +| `ownerAddress`\* | UserFriendlyAddress | The owner of the jetton wallet. | | `rawBalance`\* | TokenAmount | Balance in raw smallest units (e.g. nano) | | `decimals` | `number` | Decimals mapped from metadata if available | -| `balance` | `string` | Human readable formatted balance if decimals are known | -| `status`\* | StreamingUpdateStatus | The finality of the update | +| `balance` | `string` | Human readable formatted balance if decimals are known. | +| `status`\* | StreamingUpdateStatus | Finality stage of the update — see [`StreamingUpdateStatus`](#streamingupdatestatus). | #### JettonVerification @@ -2563,8 +2563,8 @@ Response payload of [`getJettons`](#getjettons) / [`getJettonsByAddress`](#getje | Field | Type | Description | | --- | --- | --- | -| `addressBook`\* | AddressBook | Address book mapping | -| `jettons`\* | Jetton[] | List of Jettons | +| `addressBook`\* | AddressBook | Address book mapping. | +| `jettons`\* | Jetton[] | List of Jettons. | #### TransferJettonParameters @@ -2698,20 +2698,20 @@ Non-fungible TEP-62 token held in the user's TON wallet — carries the contract | Field | Type | Description | | --- | --- | --- | -| `address`\* | UserFriendlyAddress | Contract address of the NFT item | -| `index` | `string` | Index of the item within its collection | +| `address`\* | UserFriendlyAddress | Contract address of the NFT item. | +| `index` | `string` | Index of the item within its collection. | | `info` | TokenInfo | Display information about the NFT (name, description, images) | | `attributes` | NFTAttribute[] | Custom attributes/traits of the NFT (e.g., rarity, properties) | -| `collection` | NFTCollection | Information about the collection this item belongs to | -| `auctionContractAddress` | UserFriendlyAddress | Address of the auction contract, if the NFT is being auctioned | -| `codeHash` | Hex | Hash of the NFT smart contract code | -| `dataHash` | Hex | Hash of the NFT's on-chain data | -| `isInited` | `boolean` | Whether the NFT contract has been initialized | +| `collection` | NFTCollection | Information about the collection this item belongs to. | +| `auctionContractAddress` | UserFriendlyAddress | Address of the auction contract, if the NFT is being auctioned. | +| `codeHash` | Hex | Hash of the NFT smart contract code. | +| `dataHash` | Hex | Hash of the NFT's on-chain data. | +| `isInited` | `boolean` | Whether the NFT contract has been initialized. | | `isSoulbound` | `boolean` | Whether the NFT is soulbound (non-transferable) | -| `isOnSale` | `boolean` | Whether the NFT is currently listed for sale | -| `ownerAddress` | UserFriendlyAddress | Current owner address of the NFT | +| `isOnSale` | `boolean` | Whether the NFT is currently listed for sale. | +| `ownerAddress` | UserFriendlyAddress | Current owner address of the NFT. | | `realOwnerAddress` | UserFriendlyAddress | Real owner address when NFT is on sale (sale contract becomes temporary owner) | -| `saleContractAddress` | UserFriendlyAddress | Address of the sale contract, if the NFT is listed for sale | +| `saleContractAddress` | UserFriendlyAddress | Address of the sale contract, if the NFT is listed for sale. | | `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the NFT. | #### NFTAttribute @@ -2730,15 +2730,15 @@ NFT collection (TEP-62) — surfaced as [`NFT`](#nft)'s `collection` and carries | Field | Type | Description | | --- | --- | --- | -| `address`\* | UserFriendlyAddress | The blockchain address of the NFT collection contract | -| `name` | `string` | The name of the NFT collection | -| `image` | `TokenImage` | The image representing the NFT collection | -| `description` | `string` | A brief description of the NFT collection | -| `nextItemIndex` | `string` | The index value for the next item to be minted in the collection | -| `codeHash` | Hex | The hash of the collection's smart contract code | -| `dataHash` | Hex | The hash of the collection's data in the blockchain | -| `ownerAddress` | UserFriendlyAddress | The blockchain address of the collection owner | -| `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the NFT collection | +| `address`\* | UserFriendlyAddress | The blockchain address of the NFT collection contract. | +| `name` | `string` | The name of the NFT collection. | +| `image` | `TokenImage` | The image representing the NFT collection. | +| `description` | `string` | A brief description of the NFT collection. | +| `nextItemIndex` | `string` | The index value for the next item to be minted in the collection. | +| `codeHash` | Hex | The hash of the collection's smart contract code. | +| `dataHash` | Hex | The hash of the collection's data in the blockchain. | +| `ownerAddress` | UserFriendlyAddress | The blockchain address of the collection owner. | +| `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the NFT collection. | #### NFTsResponse @@ -2746,8 +2746,8 @@ Response payload of [`getNfts`](#getnfts) / [`getNftsByAddress`](#getnftsbyaddre | Field | Type | Description | | --- | --- | --- | -| `addressBook` | AddressBook | Address book entries related to the NFTs | -| `nfts`\* | NFT[] | List of NFTs | +| `addressBook` | AddressBook | Address book entries related to the NFTs. | +| `nfts`\* | NFT[] | List of NFTs. | #### TransferNftParameters @@ -2835,11 +2835,11 @@ type NetworkAdapters = { #### NetworkConfig -Network configuration for a specific chain +Network configuration for a specific chain. | Field | Type | Description | | --- | --- | --- | -| `apiClient` | ApiClientConfig \| ApiClient | API client configuration or instance | +| `apiClient` | ApiClientConfig \| ApiClient | API client configuration or instance. | #### SetDefaultNetworkParameters @@ -2866,11 +2866,11 @@ Walletkit-side options shape consumed by [`KitNetworkManager`](#kitnetworkmanage | `walletManifest` | `WalletInfo` | TonConnect wallet manifest published by the dApp. Required for the wallet to recognize the integration. | | `deviceInfo` | `DeviceInfo` | Device fingerprint forwarded with TonConnect requests so wallets can recognize the host. | | `sessionManager` | `TONConnectSessionManager` | Custom session manager implementation. If not provided, TONConnectStoredSessionManager will be used. | -| `networks` | NetworkAdapters | Network configuration | -| `bridge` | `BridgeConfig` | Bridge settings | -| `storage` | `StorageConfig \| StorageAdapter` | Storage settings | -| `validation` | `{ strictMode?: boolean; allowUnknownWalletVersions?: boolean; }` | Validation settings | -| `eventProcessor` | `EventProcessorConfig` | Event processor settings | +| `networks` | NetworkAdapters | Network configuration. | +| `bridge` | `BridgeConfig` | Bridge settings. | +| `storage` | `StorageConfig \| StorageAdapter` | Storage settings. | +| `validation` | `{ strictMode?: boolean; allowUnknownWalletVersions?: boolean; }` | Validation settings. | +| `eventProcessor` | `EventProcessorConfig` | Event processor settings. | | `analytics` | `AnalyticsManagerOptions & { enabled?: boolean; }` | Analytics manager options merged with an `enabled` toggle. Off by default. | | `dev` | `{ disableNetworkSend?: boolean; disableManifestDomainCheck?: boolean; }` | Diagnostic toggles useful during local development. Should not be set in production builds. | @@ -3092,9 +3092,9 @@ Options for [`buildStakeTransaction`](#buildstaketransaction) — extends [`Stak | Field | Type | Description | | --- | --- | --- | -| `quote`\* | StakingQuote | The staking quote based on which the transaction is built | -| `userAddress`\* | UserFriendlyAddress | Address of the user performing the staking | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `quote`\* | StakingQuote | The staking quote based on which the transaction is built. | +| `userAddress`\* | UserFriendlyAddress | Address of the user performing the staking. | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `providerId` | `string` | Provider to stake/unstake through. Defaults to the registered default staking provider. | #### BuildStakeTransactionReturnType @@ -3196,12 +3196,12 @@ Options for [`getStakingQuote`](#getstakingquote) — extends [`StakingQuotePara | Field | Type | Description | | --- | --- | --- | | `direction`\* | StakingQuoteDirection | Direction of the quote (stake or unstake) | -| `amount`\* | `string` | Amount of tokens to stake or unstake | -| `userAddress` | UserFriendlyAddress | Address of the user | -| `network` | Network | Network on which the staking will be executed | +| `amount`\* | `string` | Amount of tokens to stake or unstake. | +| `userAddress` | UserFriendlyAddress | Address of the user. | +| `network` | Network | Network on which the staking will be executed. | | `unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | | `isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `providerId` | `string` | Provider to quote against. Defaults to the registered default staking provider. | #### GetStakingQuoteReturnType @@ -3230,13 +3230,13 @@ type SetDefaultStakingProviderReturnType = void; #### StakeParams -Parameters for staking TON +Parameters for staking TON. | Field | Type | Description | | --- | --- | --- | -| `quote`\* | StakingQuote | The staking quote based on which the transaction is built | -| `userAddress`\* | UserFriendlyAddress | Address of the user performing the staking | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `quote`\* | StakingQuote | The staking quote based on which the transaction is built. | +| `userAddress`\* | UserFriendlyAddress | Address of the user performing the staking. | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | #### StakingAPI @@ -3259,7 +3259,7 @@ Staking API interface exposed by StakingManager #### StakingBalance -Staking balance information for a user +Staking balance information for a user. | Field | Type | Description | | --- | --- | --- | @@ -3267,11 +3267,11 @@ Staking balance information for a user | `stakedBalance`\* | `string` | Amount currently staked, formatted to the stake token's decimals as a human-readable decimal string (e.g., `"12.5"`). | | `rawInstantUnstakeAvailable`\* | TokenAmount | Amount available for instant unstake, in raw smallest units of the stake token (e.g., nano-TON). | | `instantUnstakeAvailable`\* | `string` | Amount available for instant unstake, formatted to the stake token's decimals as a human-readable decimal string (e.g., `"12.5"`). | -| `providerId`\* | `string` | Identifier of the staking provider | +| `providerId`\* | `string` | Identifier of the staking provider. | #### StakingProviderInfo -Dynamic staking information for a provider +Dynamic staking information for a provider. | Field | Type | Description | | --- | --- | --- | @@ -3282,12 +3282,12 @@ Dynamic staking information for a provider #### StakingProviderMetadata -Static metadata for a staking provider +Static metadata for a staking provider. | Field | Type | Description | | --- | --- | --- | | `name`\* | `string` | Human-readable provider name (e.g. "Tonstakers") | -| `supportedUnstakeModes`\* | UnstakeModes[] | Supported unstake modes for this provider | +| `supportedUnstakeModes`\* | UnstakeModes[] | Supported unstake modes for this provider. | | `supportsReversedQuote`\* | `boolean` | Whether provider supports reversed quote format (e.g., passing TON instead of tsTON for unstake) | | `stakeToken`\* | StakingTokenInfo | Token that the user sends when staking (e.g. TON) | | `receiveToken` | StakingTokenInfo | Token that the user receives when staking (e.g. tsTON for liquid staking). Absent for direct/custodial staking. | @@ -3308,23 +3308,23 @@ Partial overrides applied on top of a provider's built-in [`StakingProviderMetad #### StakingQuote -Staking quote response with pricing information +Staking quote response with pricing information. | Field | Type | Description | | --- | --- | --- | | `direction`\* | StakingQuoteDirection | Direction of the quote (stake or unstake) | -| `rawAmountIn`\* | TokenAmount | Amount of tokens being provided | -| `rawAmountOut`\* | TokenAmount | Estimated amount of tokens to be received | -| `amountIn`\* | `string` | Formatted amount of tokens being provided | -| `amountOut`\* | `string` | Formatted estimated amount of tokens to be received | -| `network`\* | Network | Network on which the staking will be executed | -| `providerId`\* | `string` | Identifier of the staking provider | +| `rawAmountIn`\* | TokenAmount | Amount of tokens being provided. | +| `rawAmountOut`\* | TokenAmount | Estimated amount of tokens to be received. | +| `amountIn`\* | `string` | Formatted amount of tokens being provided. | +| `amountOut`\* | `string` | Formatted estimated amount of tokens to be received. | +| `network`\* | Network | Network on which the staking will be executed. | +| `providerId`\* | `string` | Identifier of the staking provider. | | `unstakeMode` | UnstakeModes | Unstake-timing mode the quote was produced for. Only meaningful when `direction === 'unstake'` — for `'stake'` it is ignored. | -| `metadata` | `unknown` | Provider-specific metadata for the quote | +| `metadata` | `unknown` | Provider-specific metadata for the quote. | #### StakingQuoteDirection -Direction of the staking quote +Direction of the staking quote. ```ts type StakingQuoteDirection = 'stake' | 'unstake'; @@ -3332,17 +3332,17 @@ type StakingQuoteDirection = 'stake' | 'unstake'; #### StakingQuoteParams -Parameters for getting a staking quote +Parameters for getting a staking quote. | Field | Type | Description | | --- | --- | --- | | `direction`\* | StakingQuoteDirection | Direction of the quote (stake or unstake) | -| `amount`\* | `string` | Amount of tokens to stake or unstake | -| `userAddress` | UserFriendlyAddress | Address of the user | -| `network` | Network | Network on which the staking will be executed | +| `amount`\* | `string` | Amount of tokens to stake or unstake. | +| `userAddress` | UserFriendlyAddress | Address of the user. | +| `network` | Network | Network on which the staking will be executed. | | `unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | | `isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | #### StakingTokenInfo @@ -3422,12 +3422,12 @@ DeDust-specific options forwarded through `providerOptions` on [`SwapQuoteParams | Field | Type | Description | | --- | --- | --- | | `protocols` | `string[]` | Protocols to use for routing. Available values: `'dedust'`, `'dedust_v3'`, `'dedust_v3_memepad'`, `'stonfi_v1'`, `'stonfi_v2'`, `'tonco'`, `'memeslab'`, `'tonfun'`. Defaults to all protocols when omitted. | -| `excludeProtocols` | `string[]` | Protocols to exclude from routing | -| `onlyVerifiedPools` | `boolean` | Only use verified pools | +| `excludeProtocols` | `string[]` | Protocols to exclude from routing. | +| `onlyVerifiedPools` | `boolean` | Only use verified pools. | | `maxSplits` | `number` | Maximum number of route splits | | `maxLength` | `number` | Maximum route length (hops) | -| `excludeVolatilePools` | `boolean` | Exclude volatile pools | -| `referralAddress` | `string` | The address of the referrer | +| `excludeVolatilePools` | `boolean` | Exclude volatile pools. | +| `referralAddress` | `string` | The address of the referrer. | | `referralFeeBps` | `number` | Referral fee in basis points (max 100 = 1%) | #### DeDustQuoteMetadata @@ -3445,7 +3445,7 @@ Optional referral metadata attached to DeDust swaps so the provider can attribut | Field | Type | Description | | --- | --- | --- | -| `referralAddress` | `string` | The address of the referrer | +| `referralAddress` | `string` | The address of the referrer. | | `referralFeeBps` | `number` | Referral fee in basis points (max 100 = 1%) | #### DeDustSwapProviderConfig @@ -3461,8 +3461,8 @@ Configuration accepted by [`createDeDustProvider`](#creatededustprovider). | `maxSplits` | `number` | Maximum number of route splits | | `maxLength` | `number` | Maximum route length (hops) | | `minPoolUsdTvl` | `string` | Minimum pool TVL in USD | -| `metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider | -| `referralAddress` | `string` | The address of the referrer | +| `metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider. | +| `referralAddress` | `string` | The address of the referrer. | | `referralFeeBps` | `number` | Referral fee in basis points (max 100 = 1%) | #### GetSwapManagerReturnType @@ -3504,12 +3504,12 @@ Options for [`getSwapQuote`](#getswapquote) — extends [`SwapQuoteParams`](#swa | Field | Type | Description | | --- | --- | --- | | `amount`\* | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | -| `from`\* | SwapToken | Token to swap from | -| `to`\* | SwapToken | Token to swap to | -| `network`\* | Network | Network on which the swap will be executed | +| `from`\* | SwapToken | Token to swap from. | +| `to`\* | SwapToken | Token to swap to. | +| `network`\* | Network | Network on which the swap will be executed. | | `slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `maxOutgoingMessages` | `number` | Maximum number of outgoing messages | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | | `providerId` | `string` | Provider to quote against. Defaults to the registered default swap provider. | @@ -3527,10 +3527,10 @@ Omniston-specific options forwarded through `providerOptions` on [`SwapQuotePara | Field | Type | Description | | --- | --- | --- | -| `settlementMethods` | `SettlementMethodValue[]` | Settlement methods to use for the swap | -| `referrerAddress` | `string` | The address of the referrer | +| `settlementMethods` | `SettlementMethodValue[]` | Settlement methods to use for the swap. | +| `referrerAddress` | `string` | The address of the referrer. | | `referrerFeeBps` | `number` | Referrer fee in basis points (1 bp = 0.01%) | -| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed | +| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed. | #### OmnistonQuoteMetadata @@ -3546,9 +3546,9 @@ Optional referrer metadata attached to Omniston swaps so the provider can attrib | Field | Type | Description | | --- | --- | --- | -| `referrerAddress` | `string` | The address of the referrer | +| `referrerAddress` | `string` | The address of the referrer. | | `referrerFeeBps` | `number` | Referrer fee in basis points (1 bp = 0.01%) | -| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed | +| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed. | #### OmnistonSwapProviderConfig @@ -3559,11 +3559,11 @@ Configuration accepted by [`createOmnistonProvider`](#createomnistonprovider). | `apiUrl` | `string` | Optional URL for the Omniston API | | `defaultSlippageBps` | `number` | Default slippage tolerance in basis points (1 bp = 0.01%) | | `quoteTimeoutMs` | `number` | Timeout for quote requests in milliseconds | -| `providerId` | `string` | Identifier for the provider | -| `metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider | -| `referrerAddress` | `string` | The address of the referrer | +| `providerId` | `string` | Identifier for the provider. | +| `metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider. | +| `referrerAddress` | `string` | The address of the referrer. | | `referrerFeeBps` | `number` | Referrer fee in basis points (1 bp = 0.01%) | -| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed | +| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed. | #### SetDefaultSwapProviderParameters @@ -3603,12 +3603,12 @@ Parameters consumed by [`buildSwapTransaction`](#buildswaptransaction) — the p | Field | Type | Description | | --- | --- | --- | -| `quote`\* | SwapQuote | The swap quote based on which the transaction is built | -| `userAddress`\* | UserFriendlyAddress | Address of the user performing the swap | +| `quote`\* | SwapQuote | The swap quote based on which the transaction is built. | +| `userAddress`\* | UserFriendlyAddress | Address of the user performing the swap. | | `destinationAddress` | UserFriendlyAddress | Address to receive the swapped tokens (defaults to userAddress) | | `slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `deadline` | `number` | Unix timestamp (in seconds) after which the swap transaction must not be executed. | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | #### SwapQuote @@ -3616,19 +3616,19 @@ Quote returned by [`getSwapQuote`](#getswapquote) — source/target tokens, expe | Field | Type | Description | | --- | --- | --- | -| `fromToken`\* | SwapToken | Token being sold | -| `toToken`\* | SwapToken | Token being bought | -| `rawFromAmount`\* | TokenAmount | Amount of tokens to sell | -| `rawToAmount`\* | TokenAmount | Amount of tokens to buy | -| `fromAmount`\* | `string` | Amount of tokens to sell | -| `toAmount`\* | `string` | Amount of tokens to buy | -| `rawMinReceived`\* | TokenAmount | Minimum amount of tokens to receive (after slippage) | -| `minReceived`\* | `string` | Minimum amount of tokens to receive (after slippage) | -| `network`\* | Network | Network on which the swap will be executed | +| `fromToken`\* | SwapToken | Token being sold. | +| `toToken`\* | SwapToken | Token being bought. | +| `rawFromAmount`\* | TokenAmount | Amount of `fromToken` to sell, in raw smallest units (e.g., nano-TON). | +| `rawToAmount`\* | TokenAmount | Amount of `toToken` to buy, in raw smallest units (e.g., nano-TON). | +| `fromAmount`\* | `string` | Amount of `fromToken` to sell, formatted to the token's decimals as a human-readable decimal string (e.g., `"1.5"`). | +| `toAmount`\* | `string` | Amount of `toToken` to buy, formatted to the token's decimals as a human-readable decimal string (e.g., `"1.5"`). | +| `rawMinReceived`\* | TokenAmount | Minimum amount of `toToken` to receive after slippage, in raw smallest units (e.g., nano-TON). | +| `minReceived`\* | `string` | Minimum amount of `toToken` to receive after slippage, formatted to the token's decimals as a human-readable decimal string (e.g., `"1.5"`). | +| `network`\* | Network | Network on which the swap will be executed. | | `priceImpact` | `number` | Price impact of the swap in basis points (100 = 1%) | -| `providerId`\* | `string` | Identifier of the swap provider | +| `providerId`\* | `string` | Identifier of the swap provider. | | `expiresAt` | `number` | Unix timestamp in seconds when the quote expires | -| `metadata` | `unknown` | Provider-specific metadata for the quote | +| `metadata` | `unknown` | Provider-specific metadata for the quote. | #### SwapQuoteParams @@ -3637,12 +3637,12 @@ Parameters consumed by [`getSwapQuote`](#getswapquote) — source/target tokens | Field | Type | Description | | --- | --- | --- | | `amount`\* | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | -| `from`\* | SwapToken | Token to swap from | -| `to`\* | SwapToken | Token to swap to | -| `network`\* | Network | Network on which the swap will be executed | +| `from`\* | SwapToken | Token to swap from. | +| `to`\* | SwapToken | Token to swap to. | +| `network`\* | Network | Network on which the swap will be executed. | | `slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `maxOutgoingMessages` | `number` | Maximum number of outgoing messages | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | #### SwapToken @@ -3740,9 +3740,9 @@ Wallet response carrying the BoC (bag of cells) of the external message that was | Field | Type | Description | | --- | --- | --- | -| `boc`\* | Base64String | BoC of the sent transaction | -| `normalizedBoc`\* | Base64String | Normalized BoC of the external-in message | -| `normalizedHash`\* | Hex | Hash of the normalized external-in message | +| `boc`\* | Base64String | BoC of the sent transaction. | +| `normalizedBoc`\* | Base64String | Normalized BoC of the external-in message. | +| `normalizedHash`\* | Hex | Hash of the normalized external-in message. | #### SendTransactionReturnType @@ -3758,26 +3758,26 @@ Single transaction record carried inside [`TransactionsUpdate`](#transactionsupd | Field | Type | Description | | --- | --- | --- | -| `account`\* | UserFriendlyAddress | Account of the transaction | -| `accountStateBefore` | `AccountState` | The state of the account before the transaction was executed | -| `accountStateAfter` | `AccountState` | The state of the account after the transaction has been applied | -| `description` | `TransactionDescription` | The detailed breakdown of the transaction execution | -| `hash`\* | Hex | Hash of the transaction | -| `logicalTime`\* | `LogicalTime` | The logical time of the transaction | -| `now`\* | `number` | Unix timestamp of the transaction | +| `account`\* | UserFriendlyAddress | Account of the transaction. | +| `accountStateBefore` | `AccountState` | The state of the account before the transaction was executed. | +| `accountStateAfter` | `AccountState` | The state of the account after the transaction has been applied. | +| `description` | `TransactionDescription` | The detailed breakdown of the transaction execution. | +| `hash`\* | Hex | Hash of the transaction. | +| `logicalTime`\* | `LogicalTime` | The logical time of the transaction. | +| `now`\* | `number` | Unix timestamp of the transaction. | | `mcBlockSeqno`\* | `number` | Masterchain block sequence number | -| `traceExternalHash`\* | Hex | External hash of the trace | -| `traceId` | `string` | ID of the trace | -| `previousTransactionHash` | `string` | The hash of the previous transaction | -| `previousTransactionLogicalTime` | `LogicalTime` | The logical time of the previous transaction | -| `origStatus` | `AccountStatus` | Original status of the transaction | -| `endStatus` | `AccountStatus` | End status of the transaction | -| `totalFees` | TokenAmount | Total fees of the transaction | -| `totalFeesExtraCurrencies` | ExtraCurrencies | Extra currencies in the total fees | -| `blockRef` | `TransactionBlockRef` | The reference to the block in which the transaction was included | -| `inMessage` | `TransactionMessage` | The incoming message associated with the transaction | -| `outMessages`\* | `TransactionMessage[]` | The list of outgoing messages produced by the transaction | -| `isEmulated`\* | `boolean` | Emulated state of the transaction | +| `traceExternalHash`\* | Hex | External hash of the trace. | +| `traceId` | `string` | ID of the trace. | +| `previousTransactionHash` | `string` | The hash of the previous transaction. | +| `previousTransactionLogicalTime` | `LogicalTime` | The logical time of the previous transaction. | +| `origStatus` | `AccountStatus` | Original status of the transaction. | +| `endStatus` | `AccountStatus` | End status of the transaction. | +| `totalFees` | TokenAmount | Total fees of the transaction. | +| `totalFeesExtraCurrencies` | ExtraCurrencies | Extra currencies in the total fees. | +| `blockRef` | `TransactionBlockRef` | The reference to the block in which the transaction was included. | +| `inMessage` | `TransactionMessage` | The incoming message associated with the transaction. | +| `outMessages`\* | `TransactionMessage[]` | The list of outgoing messages produced by the transaction. | +| `isEmulated`\* | `boolean` | Emulated state of the transaction. | #### TransactionRequest @@ -3808,13 +3808,13 @@ Update payload delivered to [`watchTransactions`](#watchtransactions) / [`watchT | Field | Type | Description | | --- | --- | --- | -| `type`\* | `'transactions'` | The update type field | -| `address`\* | UserFriendlyAddress | The account address | -| `transactions`\* | Transaction[] | The array of transactions | -| `traceHash`\* | Hex | The hash of the trace | -| `addressBook` | AddressBook | Address book from streaming v2 notification | -| `metadata` | `TransactionAddressMetadata` | Metadata from streaming v2 notification | -| `status`\* | StreamingUpdateStatus | The finality of the update | +| `type`\* | `'transactions'` | Discriminator pinned to `'transactions'` — identifies this update as a transactions stream payload. | +| `address`\* | UserFriendlyAddress | Account address the transactions belong to (the watched address). | +| `transactions`\* | Transaction[] | Transactions that landed for `address` in this update. | +| `traceHash`\* | Hex | Hash of the trace that produced these transactions — the root external-message hash that spawned them. | +| `addressBook` | AddressBook | Pre-resolved address-book entries for raw addresses referenced inside `transactions`, so the UI can render labels without extra lookups. | +| `metadata` | `TransactionAddressMetadata` | Pre-fetched address metadata (interfaces, domain) for the watched `address`. | +| `status`\* | StreamingUpdateStatus | Finality stage of the update — see [`StreamingUpdateStatus`](#streamingupdatestatus). | #### TransferTonParameters diff --git a/packages/appkit-react/docs/reference.md b/packages/appkit-react/docs/reference.md index 416a2708b..a7f9f217e 100644 --- a/packages/appkit-react/docs/reference.md +++ b/packages/appkit-react/docs/reference.md @@ -184,10 +184,10 @@ Quote a crypto-to-TON onramp — given a source asset/chain and the target TON a | `parameters.sourceCurrencyAddress` | `string` | Source crypto currency address (contract address or 0x0... for native) | | `parameters.sourceChain` | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | | `parameters.targetCurrencyAddress` | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | -| `parameters.recipientAddress` | `string` | TON address that will receive the target crypto | -| `parameters.refundAddress` | `string` | Refund address for the source crypto | +| `parameters.recipientAddress` | `string` | TON address that will receive the target crypto. | +| `parameters.refundAddress` | `string` | Refund address for the source crypto. | | `parameters.isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | -| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `parameters.providerId` | `string` | Provider to quote against. Defaults to the registered default provider. | | `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | @@ -200,8 +200,8 @@ Read the current status of a crypto-onramp deposit previously created via [`useC | Parameter | Type | Description | | --- | --- | --- | | `parameters` | [`UseCryptoOnrampStatusParameters`](#usecryptoonrampstatusparameters) | Deposit id, originating provider id and TanStack Query overrides. | -| `parameters.depositId` | `string` | Deposit id | -| `parameters.providerId` | `string` | Identifier of the provider that issued this deposit | +| `parameters.depositId` | `string` | Deposit id. | +| `parameters.providerId` | `string` | Identifier of the provider that issued this deposit. | | `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | Returns: UseCryptoOnrampStatusReturnType<selectData = GetCryptoOnrampStatusData> — TanStack Query result for the status read. @@ -858,12 +858,12 @@ Quote a stake or unstake — given an amount, direction (`'stake'` / `'unstake'` | --- | --- | --- | | `parameters` | [`UseStakingQuoteParameters`](#usestakingquoteparameters) | Quote parameters, optional `providerId`, optional network override, and TanStack Query overrides. | | `parameters.direction` | StakingQuoteDirection | Direction of the quote (stake or unstake) | -| `parameters.amount` | `string` | Amount of tokens to stake or unstake | -| `parameters.userAddress` | UserFriendlyAddress | Address of the user | -| `parameters.network` | Network | Network on which the staking will be executed | +| `parameters.amount` | `string` | Amount of tokens to stake or unstake. | +| `parameters.userAddress` | UserFriendlyAddress | Address of the user. | +| `parameters.network` | Network | Network on which the staking will be executed. | | `parameters.unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](/ecosystem/appkit/reference/appkit#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | | `parameters.isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | -| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `parameters.providerId` | `string` | Provider to quote against. Defaults to the registered default staking provider. | | `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | @@ -908,12 +908,12 @@ Quote a swap — given source/target tokens and an amount, returns the rate, exp | --- | --- | --- | | `parameters` | [`UseSwapQuoteParameters`](#useswapquoteparameters) | Source and target tokens, amount, optional network/provider override, and TanStack Query overrides. | | `parameters.amount` | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | -| `parameters.from` | SwapToken | Token to swap from | -| `parameters.to` | SwapToken | Token to swap to | -| `parameters.network` | Network | Network on which the swap will be executed | +| `parameters.from` | SwapToken | Token to swap from. | +| `parameters.to` | SwapToken | Token to swap to. | +| `parameters.network` | Network | Network on which the swap will be executed. | | `parameters.slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `parameters.maxOutgoingMessages` | `number` | Maximum number of outgoing messages | -| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `parameters.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `parameters.isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | | `parameters.providerId` | `string` | Provider to quote against. Defaults to the registered default swap provider. | | `parameters.query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | @@ -2503,10 +2503,10 @@ Parameters accepted by [`useCryptoOnrampQuote`](#usecryptoonrampquote) — TanSt | `sourceCurrencyAddress` | `string` | Source crypto currency address (contract address or 0x0... for native) | | `sourceChain` | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | | `targetCurrencyAddress` | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | -| `recipientAddress` | `string` | TON address that will receive the target crypto | -| `refundAddress` | `string` | Refund address for the source crypto | +| `recipientAddress` | `string` | TON address that will receive the target crypto. | +| `refundAddress` | `string` | Refund address for the source crypto. | | `isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `providerId` | `string` | Provider to quote against. Defaults to the registered default provider. | | `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | @@ -2527,8 +2527,8 @@ Parameters accepted by [`useCryptoOnrampStatus`](#usecryptoonrampstatus) — Tan | Field | Type | Description | | --- | --- | --- | -| `depositId` | `string` | Deposit id | -| `providerId` | `string` | Identifier of the provider that issued this deposit | +| `depositId` | `string` | Deposit id. | +| `providerId` | `string` | Identifier of the provider that issued this deposit. | | `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | #### UseCryptoOnrampStatusReturnType @@ -3380,12 +3380,12 @@ Parameters accepted by [`useStakingQuote`](#usestakingquote) — TanStack Query | Field | Type | Description | | --- | --- | --- | | `direction` | StakingQuoteDirection | Direction of the quote (stake or unstake) | -| `amount` | `string` | Amount of tokens to stake or unstake | -| `userAddress` | UserFriendlyAddress | Address of the user | -| `network` | Network | Network on which the staking will be executed | +| `amount` | `string` | Amount of tokens to stake or unstake. | +| `userAddress` | UserFriendlyAddress | Address of the user. | +| `network` | Network | Network on which the staking will be executed. | | `unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](/ecosystem/appkit/reference/appkit#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | | `isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `providerId` | `string` | Provider to quote against. Defaults to the registered default staking provider. | | `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | @@ -3596,12 +3596,12 @@ Parameters accepted by [`useSwapQuote`](#useswapquote) — TanStack Query option | Field | Type | Description | | --- | --- | --- | | `amount` | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | -| `from` | SwapToken | Token to swap from | -| `to` | SwapToken | Token to swap to | -| `network` | Network | Network on which the swap will be executed | +| `from` | SwapToken | Token to swap from. | +| `to` | SwapToken | Token to swap to. | +| `network` | Network | Network on which the swap will be executed. | | `slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `maxOutgoingMessages` | `number` | Maximum number of outgoing messages | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | | `providerId` | `string` | Provider to quote against. Defaults to the registered default swap provider. | | `query` | [`QueryOptionsOverride`](/ecosystem/appkit/reference/appkit#queryoptionsoverride) | TanStack Query options forwarded to `useQuery` (`enabled`, `staleTime`, `refetchInterval`, `select`, …). `queryKey` and `queryFn` are managed by the wrapper. | diff --git a/packages/appkit/docs/reference.md b/packages/appkit/docs/reference.md index 0e1b07d64..90383081f 100644 --- a/packages/appkit/docs/reference.md +++ b/packages/appkit/docs/reference.md @@ -345,8 +345,8 @@ Create a crypto-onramp deposit from a quote previously obtained via [`getCryptoO | `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | | `options`\* | [`CreateCryptoOnrampDepositOptions`](#createcryptoonrampdepositoptions) | Quote, refund address, and optional provider override. | | `options.quote`\* | CryptoOnrampQuote<TQuoteMetadata = unknown> | Quote to execute the deposit against (contains recipientAddress and provider metadata) | -| `options.refundAddress`\* | `string` | Address to refund the crypto to in case of failure | -| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.refundAddress`\* | `string` | Address to refund the crypto to in case of failure. | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `options.providerId` | `string` | Provider to create the deposit through. Defaults to `quote.providerId`, then to the default provider. | Returns: CreateCryptoOnrampDepositReturnType — Deposit details the UI should show to the user (address, amount, optional `memo`/`expiresAt`). @@ -422,10 +422,10 @@ Quote a crypto-to-TON onramp — given a source asset/chain and target TON asset | `options.sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | | `options.sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | | `options.targetCurrencyAddress`\* | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | -| `options.recipientAddress`\* | `string` | TON address that will receive the target crypto | -| `options.refundAddress` | `string` | Refund address for the source crypto | +| `options.recipientAddress`\* | `string` | TON address that will receive the target crypto. | +| `options.refundAddress` | `string` | Refund address for the source crypto. | | `options.isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | -| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `options.providerId` | `string` | Provider to quote against. Defaults to the registered default provider. | Returns: GetCryptoOnrampQuoteReturnType — Quote with pricing details and the provider metadata required to create a deposit. @@ -438,8 +438,8 @@ Read the current status of a crypto-onramp deposit by id — typically polled un | --- | --- | --- | | `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | | `options`\* | [`GetCryptoOnrampStatusOptions`](#getcryptoonrampstatusoptions) | Deposit id, originating provider id and optional provider override. | -| `options.depositId`\* | `string` | Deposit id | -| `options.providerId`\* | `string` | Identifier of the provider that issued this deposit | +| `options.depositId`\* | `string` | Deposit id. | +| `options.providerId`\* | `string` | Identifier of the provider that issued this deposit. | Returns: GetCryptoOnrampStatusReturnType — Current [`CryptoOnrampStatus`](#cryptoonrampstatus) of the deposit. @@ -1086,9 +1086,9 @@ Build a [`TransactionRequest`](#transactionrequest) that executes a stake or uns | --- | --- | --- | | `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | | `options`\* | [`BuildStakeTransactionOptions`](#buildstaketransactionoptions) | Quote and optional provider override. | -| `options.quote`\* | StakingQuote | The staking quote based on which the transaction is built | -| `options.userAddress`\* | UserFriendlyAddress | Address of the user performing the staking | -| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.quote`\* | StakingQuote | The staking quote based on which the transaction is built. | +| `options.userAddress`\* | UserFriendlyAddress | Address of the user performing the staking. | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `options.providerId` | `string` | Provider to stake/unstake through. Defaults to the registered default staking provider. | Returns: BuildStakeTransactionReturnType — Transaction request ready to pass to `sendTransaction`. @@ -1228,12 +1228,12 @@ Quote a stake or unstake — given the amount, direction and target asset, retur | `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | | `options`\* | [`GetStakingQuoteOptions`](#getstakingquoteoptions) | Quote parameters and optional provider override. | | `options.direction`\* | StakingQuoteDirection | Direction of the quote (stake or unstake) | -| `options.amount`\* | `string` | Amount of tokens to stake or unstake | -| `options.userAddress` | UserFriendlyAddress | Address of the user | -| `options.network` | Network | Network on which the staking will be executed | +| `options.amount`\* | `string` | Amount of tokens to stake or unstake. | +| `options.userAddress` | UserFriendlyAddress | Address of the user. | +| `options.network` | Network | Network on which the staking will be executed. | | `options.unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | | `options.isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | -| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `options.providerId` | `string` | Provider to quote against. Defaults to the registered default staking provider. | Returns: GetStakingQuoteReturnType — Quote with pricing details and provider metadata. @@ -1282,12 +1282,12 @@ Build a [`TransactionRequest`](#transactionrequest) that executes a swap previou | --- | --- | --- | | `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | | `options`\* | [`BuildSwapTransactionOptions`](#buildswaptransactionoptions) | Quote and provider-specific options. | -| `options.quote`\* | SwapQuote | The swap quote based on which the transaction is built | -| `options.userAddress`\* | UserFriendlyAddress | Address of the user performing the swap | +| `options.quote`\* | SwapQuote | The swap quote based on which the transaction is built. | +| `options.userAddress`\* | UserFriendlyAddress | Address of the user performing the swap. | | `options.destinationAddress` | UserFriendlyAddress | Address to receive the swapped tokens (defaults to userAddress) | | `options.slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `options.deadline` | `number` | Unix timestamp (in seconds) after which the swap transaction must not be executed. | -| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | Returns: BuildSwapTransactionReturnType — Transaction request ready to pass to `sendTransaction`. @@ -1386,12 +1386,12 @@ Quote a swap — given source/target tokens and an amount, returns the rate, exp | `appKit`\* | [`AppKit`](#appkit) | Runtime instance. | | `options`\* | [`GetSwapQuoteOptions`](#getswapquoteoptions) | Source and target tokens, amount, optional network and provider override. | | `options.amount`\* | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | -| `options.from`\* | SwapToken | Token to swap from | -| `options.to`\* | SwapToken | Token to swap to | -| `options.network`\* | Network | Network on which the swap will be executed | +| `options.from`\* | SwapToken | Token to swap from. | +| `options.to`\* | SwapToken | Token to swap to. | +| `options.network`\* | Network | Network on which the swap will be executed. | | `options.slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `options.maxOutgoingMessages` | `number` | Maximum number of outgoing messages | -| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `options.providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `options.isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | | `options.providerId` | `string` | Provider to quote against. Defaults to the registered default swap provider. | @@ -1811,7 +1811,7 @@ Constructor: `new LayerswapCryptoOnrampProvider(config)` | --- | --- | --- | | `config` | LayerswapProviderConfig | Optional [`LayerswapProviderConfig`](#layerswapproviderconfig). Defaults are filled in for any field left undefined. | | `config.apiKey` | `string` | Optional API key. Forwarded as `X-LS-APIKEY` when provided. | -| `config.apiUrl` | `string` | Override the base API URL. Defaults to https://api.layerswap.io/api/v2 | +| `config.apiUrl` | `string` | Override the base API URL. Defaults to https://api.layerswap.io/api/v2. | #### SwapsXyzCryptoOnrampProvider @@ -1823,7 +1823,7 @@ Constructor: `new SwapsXyzCryptoOnrampProvider(config)` | --- | --- | --- | | `config`\* | [`SwapsXyzProviderConfig`](#swapsxyzproviderconfig) | Configuration carrying the required `apiKey` plus optional URL/sender overrides. | | `config.apiKey`\* | `string` | API key issued by swaps.xyz (passed as `x-api-key`) | -| `config.apiUrl` | `string` | Override the base API URL. Defaults to https://api-v2.swaps.xyz/api | +| `config.apiUrl` | `string` | Override the base API URL. Defaults to https://api-v2.swaps.xyz/api. | | `config.defaultSender` | `string` | EVM address used as `sender` on getAction requests. Required by the API even for deposit flows where the actual payer is unknown. Defaults to a null address when omitted. | ### DeFi @@ -1921,8 +1921,8 @@ Constructor: `new DeDustSwapProvider(config)` | `config.maxSplits` | `number` | Maximum number of route splits | | `config.maxLength` | `number` | Maximum route length (hops) | | `config.minPoolUsdTvl` | `string` | Minimum pool TVL in USD | -| `config.metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider | -| `config.referralAddress` | `string` | The address of the referrer | +| `config.metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider. | +| `config.referralAddress` | `string` | The address of the referrer. | | `config.referralFeeBps` | `number` | Referral fee in basis points (max 100 = 1%) | **Example** @@ -1949,11 +1949,11 @@ Constructor: `new OmnistonSwapProvider(config)` | `config.apiUrl` | `string` | Optional URL for the Omniston API | | `config.defaultSlippageBps` | `number` | Default slippage tolerance in basis points (1 bp = 0.01%) | | `config.quoteTimeoutMs` | `number` | Timeout for quote requests in milliseconds | -| `config.providerId` | `string` | Identifier for the provider | -| `config.metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider | -| `config.referrerAddress` | `string` | The address of the referrer | +| `config.providerId` | `string` | Identifier for the provider. | +| `config.metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider. | +| `config.referrerAddress` | `string` | The address of the referrer. | | `config.referrerFeeBps` | `number` | Referrer fee in basis points (1 bp = 0.01%) | -| `config.flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed | +| `config.flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed. | **Example** @@ -2019,11 +2019,11 @@ Update payload delivered to [`watchBalance`](#watchbalance) / [`watchBalanceByAd | Field | Type | Description | | --- | --- | --- | -| `type`\* | `'balance'` | The update type field | -| `address`\* | UserFriendlyAddress | The account address | -| `rawBalance`\* | TokenAmount | The account balance in nano units | -| `balance`\* | `string` | The formatted balance | -| `status`\* | StreamingUpdateStatus | The finality of the update | +| `type`\* | `'balance'` | The update type field. | +| `address`\* | UserFriendlyAddress | The account address. | +| `rawBalance`\* | TokenAmount | The account balance in nano units. | +| `balance`\* | `string` | The formatted balance. | +| `status`\* | StreamingUpdateStatus | Finality stage of the update — see [`StreamingUpdateStatus`](#streamingupdatestatus). | #### GetBalanceByAddressOptions @@ -2119,9 +2119,9 @@ Single entry inside an [`AddressBook`](#addressbook) — pairs the user-friendly | Field | Type | Description | | --- | --- | --- | -| `address` | UserFriendlyAddress | The human-readable representation of the blockchain address | -| `domain` | `string` | The domain name associated with the address if available | -| `interfaces`\* | `string[]` | List of supported interfaces by the address | +| `address` | UserFriendlyAddress | The human-readable representation of the blockchain address. | +| `domain` | `string` | The domain name associated with the address if available. | +| `interfaces`\* | `string[]` | List of supported interfaces by the address. | #### ApiClient @@ -2206,10 +2206,10 @@ Display metadata for a token (TON, jetton, or NFT) — name, symbol, image and a | Field | Type | Description | | --- | --- | --- | -| `name` | `string` | Display name of the token | -| `description` | `string` | Human-readable description of the token | -| `image` | `TokenImage` | Token image in various sizes | -| `animation` | `TokenAnimation` | Animated media associated with the token | +| `name` | `string` | Display name of the token. | +| `description` | `string` | Human-readable description of the token. | +| `image` | `TokenImage` | Token image in various sizes. | +| `animation` | `TokenAnimation` | Animated media associated with the token. | | `symbol` | `string` | Ticker symbol of the token (e.g., "TON", "USDT") | ### Connectors @@ -2523,8 +2523,8 @@ Options for [`createCryptoOnrampDeposit`](#createcryptoonrampdeposit) — extend | Field | Type | Description | | --- | --- | --- | | `quote`\* | CryptoOnrampQuote<TQuoteMetadata = unknown> | Quote to execute the deposit against (contains recipientAddress and provider metadata) | -| `refundAddress`\* | `string` | Address to refund the crypto to in case of failure | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `refundAddress`\* | `string` | Address to refund the crypto to in case of failure. | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `providerId` | `string` | Provider to create the deposit through. Defaults to `quote.providerId`, then to the default provider. | #### CreateCryptoOnrampDepositReturnType @@ -2544,15 +2544,15 @@ to complete the onramp. The provider then delivers the target crypto to the user | Field | Type | Description | | --- | --- | --- | -| `depositId`\* | `string` | Deposit id | -| `address`\* | `string` | Deposit address on the source chain | -| `amount`\* | `string` | Exact amount of source crypto the user must send | +| `depositId`\* | `string` | Deposit id. | +| `address`\* | `string` | Deposit address on the source chain. | +| `amount`\* | `string` | Exact amount of source crypto the user must send. | | `sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | | `sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:42161'). | | `memo` | `string` | Optional memo / tag required by some chains (e.g. XRP, TON comment) | -| `expiresAt` | `number` | Unix timestamp (ms) after which the deposit offer is no longer valid | +| `expiresAt` | `number` | Unix timestamp (ms) after which the deposit offer is no longer valid. | | `chainWarning` | `string` | Chain-specific warning to show the user (e.g. "send only on Solana") | -| `providerId`\* | `string` | Identifier of the provider that issued this deposit | +| `providerId`\* | `string` | Identifier of the provider that issued this deposit. | #### CryptoOnrampDepositParams @@ -2563,8 +2563,8 @@ The recipient is taken from `quote.recipientAddress` set at quote time. | Field | Type | Description | | --- | --- | --- | | `quote`\* | CryptoOnrampQuote<TQuoteMetadata = unknown> | Quote to execute the deposit against (contains recipientAddress and provider metadata) | -| `refundAddress`\* | `string` | Address to refund the crypto to in case of failure | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `refundAddress`\* | `string` | Address to refund the crypto to in case of failure. | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | #### CryptoOnrampProviderInterface @@ -2587,8 +2587,8 @@ Static metadata for a crypto-onramp provider. | Field | Type | Description | | --- | --- | --- | | `name`\* | `string` | Human-readable provider name (e.g. 'Swaps.xyz') | -| `logo` | `string` | URL to the provider's logo image | -| `url` | `string` | URL to the provider's website | +| `logo` | `string` | URL to the provider's logo image. | +| `url` | `string` | URL to the provider's website. | | `isRefundAddressRequired` | `boolean` | Whether this provider requires a refund address on the source chain. When true, the UI must collect a refund address before creating a deposit. | | `isReversedAmountSupported` | `boolean` | Whether this provider supports reversed (target-amount) quotes. When false, the UI should hide the direction toggle and only allow source-amount input. | @@ -2598,24 +2598,24 @@ Used in provider configuration to override fields of the provider's metadata. | Field | Type | Description | | --- | --- | --- | -| `name` | `string` | Override the provider's display name | -| `logo` | `string` | Override the provider's logo URL | -| `url` | `string` | Override the provider's website URL | +| `name` | `string` | Override the provider's display name. | +| `logo` | `string` | Override the provider's logo URL. | +| `url` | `string` | Override the provider's website URL. | #### CryptoOnrampQuote -Crypto onramp quote response with pricing information +Crypto onramp quote response with pricing information. | Field | Type | Description | | --- | --- | --- | | `sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | | `sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:42161'). | | `targetCurrencyAddress`\* | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | -| `sourceAmount`\* | `string` | Amount of source crypto to send | -| `targetAmount`\* | `string` | Amount of target crypto to receive | +| `sourceAmount`\* | `string` | Amount of source crypto to send. | +| `targetAmount`\* | `string` | Amount of target crypto to receive. | | `rate`\* | `string` | Exchange rate (amount of target per 1 unit of source) | -| `recipientAddress`\* | `string` | TON address that will receive the target crypto | -| `providerId`\* | `string` | Identifier of the crypto onramp provider | +| `recipientAddress`\* | `string` | TON address that will receive the target crypto. | +| `providerId`\* | `string` | Identifier of the crypto onramp provider. | | `metadata` | `TMetadata = unknown` | Provider-specific metadata for the quote (e.g. raw response needed to execute) | #### CryptoOnrampQuoteParams @@ -2630,10 +2630,10 @@ The target network is always TON, so only the source side is parameterised. | `sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | | `sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | | `targetCurrencyAddress`\* | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | -| `recipientAddress`\* | `string` | TON address that will receive the target crypto | -| `refundAddress` | `string` | Refund address for the source crypto | +| `recipientAddress`\* | `string` | TON address that will receive the target crypto. | +| `refundAddress` | `string` | Refund address for the source crypto. | | `isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | #### CryptoOnrampStatus @@ -2649,8 +2649,8 @@ Parameters accepted by [`getCryptoOnrampStatus`](#getcryptoonrampstatus) — ide | Field | Type | Description | | --- | --- | --- | -| `depositId`\* | `string` | Deposit id | -| `providerId`\* | `string` | Identifier of the provider that issued this deposit | +| `depositId`\* | `string` | Deposit id. | +| `providerId`\* | `string` | Identifier of the provider that issued this deposit. | #### GetCryptoOnrampProviderOptions @@ -2686,10 +2686,10 @@ Options for [`getCryptoOnrampQuote`](#getcryptoonrampquote) — extends [`Crypto | `sourceCurrencyAddress`\* | `string` | Source crypto currency address (contract address or 0x0... for native) | | `sourceChain`\* | `string` | Source chain identifier in CAIP-2 format (e.g. 'eip155:1' for Ethereum mainnet, 'eip155:42161' for Arbitrum One). Providers map this to their own chain identifiers internally. | | `targetCurrencyAddress`\* | `string` | Target crypto currency address on TON (contract address or 0x0... for native) | -| `recipientAddress`\* | `string` | TON address that will receive the target crypto | -| `refundAddress` | `string` | Refund address for the source crypto | +| `recipientAddress`\* | `string` | TON address that will receive the target crypto. | +| `refundAddress` | `string` | Refund address for the source crypto. | | `isSourceAmount` | `boolean` | If true, `amount` is the source amount to spend. If false, `amount` is the target amount to receive. Defaults to true when omitted. | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `providerId` | `string` | Provider to quote against. Defaults to the registered default provider. | #### GetCryptoOnrampQuoteReturnType @@ -2706,8 +2706,8 @@ Options for [`getCryptoOnrampStatus`](#getcryptoonrampstatus) — extends [`Cryp | Field | Type | Description | | --- | --- | --- | -| `depositId`\* | `string` | Deposit id | -| `providerId`\* | `string` | Identifier of the provider that issued this deposit | +| `depositId`\* | `string` | Deposit id. | +| `providerId`\* | `string` | Identifier of the provider that issued this deposit. | #### GetCryptoOnrampStatusReturnType @@ -2724,7 +2724,7 @@ Configuration accepted by [`createLayerswapProvider`](#createlayerswapprovider). | Field | Type | Description | | --- | --- | --- | | `apiKey` | `string` | Optional API key. Forwarded as `X-LS-APIKEY` when provided. | -| `apiUrl` | `string` | Override the base API URL. Defaults to https://api.layerswap.io/api/v2 | +| `apiUrl` | `string` | Override the base API URL. Defaults to https://api.layerswap.io/api/v2. | #### LayerswapQuoteMetadata @@ -2744,7 +2744,7 @@ Configuration accepted by [`createSwapsXyzProvider`](#createswapsxyzprovider). | Field | Type | Description | | --- | --- | --- | | `apiKey`\* | `string` | API key issued by swaps.xyz (passed as `x-api-key`) | -| `apiUrl` | `string` | Override the base API URL. Defaults to https://api-v2.swaps.xyz/api | +| `apiUrl` | `string` | Override the base API URL. Defaults to https://api-v2.swaps.xyz/api. | | `defaultSender` | `string` | EVM address used as `sender` on getAction requests. Required by the API even for deposit flows where the actual payer is unknown. Defaults to a null address when omitted. | #### SwapsXyzQuoteMetadata @@ -2960,12 +2960,12 @@ Fungible TEP-74 token held in the user's TON wallet — carries the master contr | --- | --- | --- | | `address`\* | UserFriendlyAddress | The jetton master contract address (the token itself). | | `walletAddress`\* | UserFriendlyAddress | The owner's jetton-wallet contract address — the per-owner contract that actually holds this balance. | -| `balance`\* | TokenAmount | The current jetton balance | -| `info`\* | TokenInfo | Information about the token | +| `balance`\* | TokenAmount | The current jetton balance. | +| `info`\* | TokenInfo | Information about the token. | | `decimalsNumber` | `number` | The number of decimal places used by the token | -| `isVerified`\* | `boolean` | Indicates if the jetton is verified | -| `prices`\* | `JettonPrice[]` | Current prices of the jetton in various currencies | -| `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the jetton | +| `isVerified`\* | `boolean` | Indicates if the jetton is verified. | +| `prices`\* | `JettonPrice[]` | Current prices of the jetton in various currencies. | +| `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the jetton. | #### JettonInfo @@ -2991,14 +2991,14 @@ Update payload delivered to [`watchJettons`](#watchjettons) / [`watchJettonsByAd | Field | Type | Description | | --- | --- | --- | -| `type`\* | `'jettons'` | The update type field | -| `masterAddress`\* | UserFriendlyAddress | The master jetton contract address | -| `walletAddress`\* | UserFriendlyAddress | The jetton wallet contract address | -| `ownerAddress`\* | UserFriendlyAddress | The owner of the jetton wallet | +| `type`\* | `'jettons'` | The update type field. | +| `masterAddress`\* | UserFriendlyAddress | The master jetton contract address. | +| `walletAddress`\* | UserFriendlyAddress | The jetton wallet contract address. | +| `ownerAddress`\* | UserFriendlyAddress | The owner of the jetton wallet. | | `rawBalance`\* | TokenAmount | Balance in raw smallest units (e.g. nano) | | `decimals` | `number` | Decimals mapped from metadata if available | -| `balance` | `string` | Human readable formatted balance if decimals are known | -| `status`\* | StreamingUpdateStatus | The finality of the update | +| `balance` | `string` | Human readable formatted balance if decimals are known. | +| `status`\* | StreamingUpdateStatus | Finality stage of the update — see [`StreamingUpdateStatus`](#streamingupdatestatus). | #### JettonVerification @@ -3016,8 +3016,8 @@ Response payload of [`getJettons`](#getjettons) / [`getJettonsByAddress`](#getje | Field | Type | Description | | --- | --- | --- | -| `addressBook`\* | AddressBook | Address book mapping | -| `jettons`\* | Jetton[] | List of Jettons | +| `addressBook`\* | AddressBook | Address book mapping. | +| `jettons`\* | Jetton[] | List of Jettons. | #### TransferJettonParameters @@ -3151,20 +3151,20 @@ Non-fungible TEP-62 token held in the user's TON wallet — carries the contract | Field | Type | Description | | --- | --- | --- | -| `address`\* | UserFriendlyAddress | Contract address of the NFT item | -| `index` | `string` | Index of the item within its collection | +| `address`\* | UserFriendlyAddress | Contract address of the NFT item. | +| `index` | `string` | Index of the item within its collection. | | `info` | TokenInfo | Display information about the NFT (name, description, images) | | `attributes` | NFTAttribute[] | Custom attributes/traits of the NFT (e.g., rarity, properties) | -| `collection` | NFTCollection | Information about the collection this item belongs to | -| `auctionContractAddress` | UserFriendlyAddress | Address of the auction contract, if the NFT is being auctioned | -| `codeHash` | Hex | Hash of the NFT smart contract code | -| `dataHash` | Hex | Hash of the NFT's on-chain data | -| `isInited` | `boolean` | Whether the NFT contract has been initialized | +| `collection` | NFTCollection | Information about the collection this item belongs to. | +| `auctionContractAddress` | UserFriendlyAddress | Address of the auction contract, if the NFT is being auctioned. | +| `codeHash` | Hex | Hash of the NFT smart contract code. | +| `dataHash` | Hex | Hash of the NFT's on-chain data. | +| `isInited` | `boolean` | Whether the NFT contract has been initialized. | | `isSoulbound` | `boolean` | Whether the NFT is soulbound (non-transferable) | -| `isOnSale` | `boolean` | Whether the NFT is currently listed for sale | -| `ownerAddress` | UserFriendlyAddress | Current owner address of the NFT | +| `isOnSale` | `boolean` | Whether the NFT is currently listed for sale. | +| `ownerAddress` | UserFriendlyAddress | Current owner address of the NFT. | | `realOwnerAddress` | UserFriendlyAddress | Real owner address when NFT is on sale (sale contract becomes temporary owner) | -| `saleContractAddress` | UserFriendlyAddress | Address of the sale contract, if the NFT is listed for sale | +| `saleContractAddress` | UserFriendlyAddress | Address of the sale contract, if the NFT is listed for sale. | | `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the NFT. | #### NFTAttribute @@ -3183,15 +3183,15 @@ NFT collection (TEP-62) — surfaced as [`NFT`](#nft)'s `collection` and carries | Field | Type | Description | | --- | --- | --- | -| `address`\* | UserFriendlyAddress | The blockchain address of the NFT collection contract | -| `name` | `string` | The name of the NFT collection | -| `image` | `TokenImage` | The image representing the NFT collection | -| `description` | `string` | A brief description of the NFT collection | -| `nextItemIndex` | `string` | The index value for the next item to be minted in the collection | -| `codeHash` | Hex | The hash of the collection's smart contract code | -| `dataHash` | Hex | The hash of the collection's data in the blockchain | -| `ownerAddress` | UserFriendlyAddress | The blockchain address of the collection owner | -| `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the NFT collection | +| `address`\* | UserFriendlyAddress | The blockchain address of the NFT collection contract. | +| `name` | `string` | The name of the NFT collection. | +| `image` | `TokenImage` | The image representing the NFT collection. | +| `description` | `string` | A brief description of the NFT collection. | +| `nextItemIndex` | `string` | The index value for the next item to be minted in the collection. | +| `codeHash` | Hex | The hash of the collection's smart contract code. | +| `dataHash` | Hex | The hash of the collection's data in the blockchain. | +| `ownerAddress` | UserFriendlyAddress | The blockchain address of the collection owner. | +| `extra` | `{ [key: string]: unknown; }` | Additional arbitrary data related to the NFT collection. | #### NFTsResponse @@ -3199,8 +3199,8 @@ Response payload of [`getNfts`](#getnfts) / [`getNftsByAddress`](#getnftsbyaddre | Field | Type | Description | | --- | --- | --- | -| `addressBook` | AddressBook | Address book entries related to the NFTs | -| `nfts`\* | NFT[] | List of NFTs | +| `addressBook` | AddressBook | Address book entries related to the NFTs. | +| `nfts`\* | NFT[] | List of NFTs. | #### TransferNftParameters @@ -3288,11 +3288,11 @@ type NetworkAdapters = { #### NetworkConfig -Network configuration for a specific chain +Network configuration for a specific chain. | Field | Type | Description | | --- | --- | --- | -| `apiClient` | ApiClientConfig \| ApiClient | API client configuration or instance | +| `apiClient` | ApiClientConfig \| ApiClient | API client configuration or instance. | #### SetDefaultNetworkParameters @@ -3319,11 +3319,11 @@ Walletkit-side options shape consumed by [`KitNetworkManager`](#kitnetworkmanage | `walletManifest` | `WalletInfo` | TonConnect wallet manifest published by the dApp. Required for the wallet to recognize the integration. | | `deviceInfo` | `DeviceInfo` | Device fingerprint forwarded with TonConnect requests so wallets can recognize the host. | | `sessionManager` | `TONConnectSessionManager` | Custom session manager implementation. If not provided, TONConnectStoredSessionManager will be used. | -| `networks` | NetworkAdapters | Network configuration | -| `bridge` | `BridgeConfig` | Bridge settings | -| `storage` | `StorageConfig \| StorageAdapter` | Storage settings | -| `validation` | `{ strictMode?: boolean; allowUnknownWalletVersions?: boolean; }` | Validation settings | -| `eventProcessor` | `EventProcessorConfig` | Event processor settings | +| `networks` | NetworkAdapters | Network configuration. | +| `bridge` | `BridgeConfig` | Bridge settings. | +| `storage` | `StorageConfig \| StorageAdapter` | Storage settings. | +| `validation` | `{ strictMode?: boolean; allowUnknownWalletVersions?: boolean; }` | Validation settings. | +| `eventProcessor` | `EventProcessorConfig` | Event processor settings. | | `analytics` | `AnalyticsManagerOptions & { enabled?: boolean; }` | Analytics manager options merged with an `enabled` toggle. Off by default. | | `dev` | `{ disableNetworkSend?: boolean; disableManifestDomainCheck?: boolean; }` | Diagnostic toggles useful during local development. Should not be set in production builds. | @@ -3545,9 +3545,9 @@ Options for [`buildStakeTransaction`](#buildstaketransaction) — extends [`Stak | Field | Type | Description | | --- | --- | --- | -| `quote`\* | StakingQuote | The staking quote based on which the transaction is built | -| `userAddress`\* | UserFriendlyAddress | Address of the user performing the staking | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `quote`\* | StakingQuote | The staking quote based on which the transaction is built. | +| `userAddress`\* | UserFriendlyAddress | Address of the user performing the staking. | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `providerId` | `string` | Provider to stake/unstake through. Defaults to the registered default staking provider. | #### BuildStakeTransactionReturnType @@ -3649,12 +3649,12 @@ Options for [`getStakingQuote`](#getstakingquote) — extends [`StakingQuotePara | Field | Type | Description | | --- | --- | --- | | `direction`\* | StakingQuoteDirection | Direction of the quote (stake or unstake) | -| `amount`\* | `string` | Amount of tokens to stake or unstake | -| `userAddress` | UserFriendlyAddress | Address of the user | -| `network` | Network | Network on which the staking will be executed | +| `amount`\* | `string` | Amount of tokens to stake or unstake. | +| `userAddress` | UserFriendlyAddress | Address of the user. | +| `network` | Network | Network on which the staking will be executed. | | `unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | | `isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `providerId` | `string` | Provider to quote against. Defaults to the registered default staking provider. | #### GetStakingQuoteReturnType @@ -3683,13 +3683,13 @@ type SetDefaultStakingProviderReturnType = void; #### StakeParams -Parameters for staking TON +Parameters for staking TON. | Field | Type | Description | | --- | --- | --- | -| `quote`\* | StakingQuote | The staking quote based on which the transaction is built | -| `userAddress`\* | UserFriendlyAddress | Address of the user performing the staking | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `quote`\* | StakingQuote | The staking quote based on which the transaction is built. | +| `userAddress`\* | UserFriendlyAddress | Address of the user performing the staking. | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | #### StakingAPI @@ -3712,7 +3712,7 @@ Staking API interface exposed by StakingManager #### StakingBalance -Staking balance information for a user +Staking balance information for a user. | Field | Type | Description | | --- | --- | --- | @@ -3720,11 +3720,11 @@ Staking balance information for a user | `stakedBalance`\* | `string` | Amount currently staked, formatted to the stake token's decimals as a human-readable decimal string (e.g., `"12.5"`). | | `rawInstantUnstakeAvailable`\* | TokenAmount | Amount available for instant unstake, in raw smallest units of the stake token (e.g., nano-TON). | | `instantUnstakeAvailable`\* | `string` | Amount available for instant unstake, formatted to the stake token's decimals as a human-readable decimal string (e.g., `"12.5"`). | -| `providerId`\* | `string` | Identifier of the staking provider | +| `providerId`\* | `string` | Identifier of the staking provider. | #### StakingProviderInfo -Dynamic staking information for a provider +Dynamic staking information for a provider. | Field | Type | Description | | --- | --- | --- | @@ -3735,12 +3735,12 @@ Dynamic staking information for a provider #### StakingProviderMetadata -Static metadata for a staking provider +Static metadata for a staking provider. | Field | Type | Description | | --- | --- | --- | | `name`\* | `string` | Human-readable provider name (e.g. "Tonstakers") | -| `supportedUnstakeModes`\* | UnstakeModes[] | Supported unstake modes for this provider | +| `supportedUnstakeModes`\* | UnstakeModes[] | Supported unstake modes for this provider. | | `supportsReversedQuote`\* | `boolean` | Whether provider supports reversed quote format (e.g., passing TON instead of tsTON for unstake) | | `stakeToken`\* | StakingTokenInfo | Token that the user sends when staking (e.g. TON) | | `receiveToken` | StakingTokenInfo | Token that the user receives when staking (e.g. tsTON for liquid staking). Absent for direct/custodial staking. | @@ -3761,23 +3761,23 @@ Partial overrides applied on top of a provider's built-in [`StakingProviderMetad #### StakingQuote -Staking quote response with pricing information +Staking quote response with pricing information. | Field | Type | Description | | --- | --- | --- | | `direction`\* | StakingQuoteDirection | Direction of the quote (stake or unstake) | -| `rawAmountIn`\* | TokenAmount | Amount of tokens being provided | -| `rawAmountOut`\* | TokenAmount | Estimated amount of tokens to be received | -| `amountIn`\* | `string` | Formatted amount of tokens being provided | -| `amountOut`\* | `string` | Formatted estimated amount of tokens to be received | -| `network`\* | Network | Network on which the staking will be executed | -| `providerId`\* | `string` | Identifier of the staking provider | +| `rawAmountIn`\* | TokenAmount | Amount of tokens being provided. | +| `rawAmountOut`\* | TokenAmount | Estimated amount of tokens to be received. | +| `amountIn`\* | `string` | Formatted amount of tokens being provided. | +| `amountOut`\* | `string` | Formatted estimated amount of tokens to be received. | +| `network`\* | Network | Network on which the staking will be executed. | +| `providerId`\* | `string` | Identifier of the staking provider. | | `unstakeMode` | UnstakeModes | Unstake-timing mode the quote was produced for. Only meaningful when `direction === 'unstake'` — for `'stake'` it is ignored. | -| `metadata` | `unknown` | Provider-specific metadata for the quote | +| `metadata` | `unknown` | Provider-specific metadata for the quote. | #### StakingQuoteDirection -Direction of the staking quote +Direction of the staking quote. ```ts type StakingQuoteDirection = 'stake' | 'unstake'; @@ -3785,17 +3785,17 @@ type StakingQuoteDirection = 'stake' | 'unstake'; #### StakingQuoteParams -Parameters for getting a staking quote +Parameters for getting a staking quote. | Field | Type | Description | | --- | --- | --- | | `direction`\* | StakingQuoteDirection | Direction of the quote (stake or unstake) | -| `amount`\* | `string` | Amount of tokens to stake or unstake | -| `userAddress` | UserFriendlyAddress | Address of the user | -| `network` | Network | Network on which the staking will be executed | +| `amount`\* | `string` | Amount of tokens to stake or unstake. | +| `userAddress` | UserFriendlyAddress | Address of the user. | +| `network` | Network | Network on which the staking will be executed. | | `unstakeMode` | UnstakeModes | Unstake-timing mode the quote should target — see [`UnstakeMode`](#unstakemode) for the supported flavours (`'INSTANT'`, `'WHEN_AVAILABLE'`, `'ROUND_END'`). Only meaningful when `direction === 'unstake'` and the provider lists the mode in `supportedUnstakeModes`. | | `isReversed` | `boolean` | If true, for unstake requests the amount is specified in the staking coin (e.g. TON) instead of the Liquid Staking Token (e.g. tsTON). | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | #### StakingTokenInfo @@ -3875,12 +3875,12 @@ DeDust-specific options forwarded through `providerOptions` on [`SwapQuoteParams | Field | Type | Description | | --- | --- | --- | | `protocols` | `string[]` | Protocols to use for routing. Available values: `'dedust'`, `'dedust_v3'`, `'dedust_v3_memepad'`, `'stonfi_v1'`, `'stonfi_v2'`, `'tonco'`, `'memeslab'`, `'tonfun'`. Defaults to all protocols when omitted. | -| `excludeProtocols` | `string[]` | Protocols to exclude from routing | -| `onlyVerifiedPools` | `boolean` | Only use verified pools | +| `excludeProtocols` | `string[]` | Protocols to exclude from routing. | +| `onlyVerifiedPools` | `boolean` | Only use verified pools. | | `maxSplits` | `number` | Maximum number of route splits | | `maxLength` | `number` | Maximum route length (hops) | -| `excludeVolatilePools` | `boolean` | Exclude volatile pools | -| `referralAddress` | `string` | The address of the referrer | +| `excludeVolatilePools` | `boolean` | Exclude volatile pools. | +| `referralAddress` | `string` | The address of the referrer. | | `referralFeeBps` | `number` | Referral fee in basis points (max 100 = 1%) | #### DeDustQuoteMetadata @@ -3898,7 +3898,7 @@ Optional referral metadata attached to DeDust swaps so the provider can attribut | Field | Type | Description | | --- | --- | --- | -| `referralAddress` | `string` | The address of the referrer | +| `referralAddress` | `string` | The address of the referrer. | | `referralFeeBps` | `number` | Referral fee in basis points (max 100 = 1%) | #### DeDustSwapProviderConfig @@ -3914,8 +3914,8 @@ Configuration accepted by [`createDeDustProvider`](#creatededustprovider). | `maxSplits` | `number` | Maximum number of route splits | | `maxLength` | `number` | Maximum route length (hops) | | `minPoolUsdTvl` | `string` | Minimum pool TVL in USD | -| `metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider | -| `referralAddress` | `string` | The address of the referrer | +| `metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider. | +| `referralAddress` | `string` | The address of the referrer. | | `referralFeeBps` | `number` | Referral fee in basis points (max 100 = 1%) | #### GetSwapManagerReturnType @@ -3957,12 +3957,12 @@ Options for [`getSwapQuote`](#getswapquote) — extends [`SwapQuoteParams`](#swa | Field | Type | Description | | --- | --- | --- | | `amount`\* | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | -| `from`\* | SwapToken | Token to swap from | -| `to`\* | SwapToken | Token to swap to | -| `network`\* | Network | Network on which the swap will be executed | +| `from`\* | SwapToken | Token to swap from. | +| `to`\* | SwapToken | Token to swap to. | +| `network`\* | Network | Network on which the swap will be executed. | | `slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `maxOutgoingMessages` | `number` | Maximum number of outgoing messages | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | | `providerId` | `string` | Provider to quote against. Defaults to the registered default swap provider. | @@ -3980,10 +3980,10 @@ Omniston-specific options forwarded through `providerOptions` on [`SwapQuotePara | Field | Type | Description | | --- | --- | --- | -| `settlementMethods` | `SettlementMethodValue[]` | Settlement methods to use for the swap | -| `referrerAddress` | `string` | The address of the referrer | +| `settlementMethods` | `SettlementMethodValue[]` | Settlement methods to use for the swap. | +| `referrerAddress` | `string` | The address of the referrer. | | `referrerFeeBps` | `number` | Referrer fee in basis points (1 bp = 0.01%) | -| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed | +| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed. | #### OmnistonQuoteMetadata @@ -3999,9 +3999,9 @@ Optional referrer metadata attached to Omniston swaps so the provider can attrib | Field | Type | Description | | --- | --- | --- | -| `referrerAddress` | `string` | The address of the referrer | +| `referrerAddress` | `string` | The address of the referrer. | | `referrerFeeBps` | `number` | Referrer fee in basis points (1 bp = 0.01%) | -| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed | +| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed. | #### OmnistonSwapProviderConfig @@ -4012,11 +4012,11 @@ Configuration accepted by [`createOmnistonProvider`](#createomnistonprovider). | `apiUrl` | `string` | Optional URL for the Omniston API | | `defaultSlippageBps` | `number` | Default slippage tolerance in basis points (1 bp = 0.01%) | | `quoteTimeoutMs` | `number` | Timeout for quote requests in milliseconds | -| `providerId` | `string` | Identifier for the provider | -| `metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider | -| `referrerAddress` | `string` | The address of the referrer | +| `providerId` | `string` | Identifier for the provider. | +| `metadata` | `SwapProviderMetadataOverride` | Custom metadata for the provider. | +| `referrerAddress` | `string` | The address of the referrer. | | `referrerFeeBps` | `number` | Referrer fee in basis points (1 bp = 0.01%) | -| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed | +| `flexibleReferrerFee` | `boolean` | Whether a flexible referrer fee is allowed. | #### SetDefaultSwapProviderParameters @@ -4056,12 +4056,12 @@ Parameters consumed by [`buildSwapTransaction`](#buildswaptransaction) — the p | Field | Type | Description | | --- | --- | --- | -| `quote`\* | SwapQuote | The swap quote based on which the transaction is built | -| `userAddress`\* | UserFriendlyAddress | Address of the user performing the swap | +| `quote`\* | SwapQuote | The swap quote based on which the transaction is built. | +| `userAddress`\* | UserFriendlyAddress | Address of the user performing the swap. | | `destinationAddress` | UserFriendlyAddress | Address to receive the swapped tokens (defaults to userAddress) | | `slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `deadline` | `number` | Unix timestamp (in seconds) after which the swap transaction must not be executed. | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | #### SwapQuote @@ -4069,19 +4069,19 @@ Quote returned by [`getSwapQuote`](#getswapquote) — source/target tokens, expe | Field | Type | Description | | --- | --- | --- | -| `fromToken`\* | SwapToken | Token being sold | -| `toToken`\* | SwapToken | Token being bought | -| `rawFromAmount`\* | TokenAmount | Amount of tokens to sell | -| `rawToAmount`\* | TokenAmount | Amount of tokens to buy | -| `fromAmount`\* | `string` | Amount of tokens to sell | -| `toAmount`\* | `string` | Amount of tokens to buy | -| `rawMinReceived`\* | TokenAmount | Minimum amount of tokens to receive (after slippage) | -| `minReceived`\* | `string` | Minimum amount of tokens to receive (after slippage) | -| `network`\* | Network | Network on which the swap will be executed | +| `fromToken`\* | SwapToken | Token being sold. | +| `toToken`\* | SwapToken | Token being bought. | +| `rawFromAmount`\* | TokenAmount | Amount of `fromToken` to sell, in raw smallest units (e.g., nano-TON). | +| `rawToAmount`\* | TokenAmount | Amount of `toToken` to buy, in raw smallest units (e.g., nano-TON). | +| `fromAmount`\* | `string` | Amount of `fromToken` to sell, formatted to the token's decimals as a human-readable decimal string (e.g., `"1.5"`). | +| `toAmount`\* | `string` | Amount of `toToken` to buy, formatted to the token's decimals as a human-readable decimal string (e.g., `"1.5"`). | +| `rawMinReceived`\* | TokenAmount | Minimum amount of `toToken` to receive after slippage, in raw smallest units (e.g., nano-TON). | +| `minReceived`\* | `string` | Minimum amount of `toToken` to receive after slippage, formatted to the token's decimals as a human-readable decimal string (e.g., `"1.5"`). | +| `network`\* | Network | Network on which the swap will be executed. | | `priceImpact` | `number` | Price impact of the swap in basis points (100 = 1%) | -| `providerId`\* | `string` | Identifier of the swap provider | +| `providerId`\* | `string` | Identifier of the swap provider. | | `expiresAt` | `number` | Unix timestamp in seconds when the quote expires | -| `metadata` | `unknown` | Provider-specific metadata for the quote | +| `metadata` | `unknown` | Provider-specific metadata for the quote. | #### SwapQuoteParams @@ -4090,12 +4090,12 @@ Parameters consumed by [`getSwapQuote`](#getswapquote) — source/target tokens | Field | Type | Description | | --- | --- | --- | | `amount`\* | `string` | Amount of tokens to swap (incoming or outgoing depending on isReverseSwap) | -| `from`\* | SwapToken | Token to swap from | -| `to`\* | SwapToken | Token to swap to | -| `network`\* | Network | Network on which the swap will be executed | +| `from`\* | SwapToken | Token to swap from. | +| `to`\* | SwapToken | Token to swap to. | +| `network`\* | Network | Network on which the swap will be executed. | | `slippageBps` | `number` | Slippage tolerance in basis points (1 bp = 0.01%) | | `maxOutgoingMessages` | `number` | Maximum number of outgoing messages | -| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options | +| `providerOptions` | `TProviderOptions = unknown` | Provider-specific options. | | `isReverseSwap` | `boolean` | If true, amount is the amount to receive (buy). If false, amount is the amount to spend (sell). | #### SwapToken @@ -4193,9 +4193,9 @@ Wallet response carrying the BoC (bag of cells) of the external message that was | Field | Type | Description | | --- | --- | --- | -| `boc`\* | Base64String | BoC of the sent transaction | -| `normalizedBoc`\* | Base64String | Normalized BoC of the external-in message | -| `normalizedHash`\* | Hex | Hash of the normalized external-in message | +| `boc`\* | Base64String | BoC of the sent transaction. | +| `normalizedBoc`\* | Base64String | Normalized BoC of the external-in message. | +| `normalizedHash`\* | Hex | Hash of the normalized external-in message. | #### SendTransactionReturnType @@ -4211,26 +4211,26 @@ Single transaction record carried inside [`TransactionsUpdate`](#transactionsupd | Field | Type | Description | | --- | --- | --- | -| `account`\* | UserFriendlyAddress | Account of the transaction | -| `accountStateBefore` | `AccountState` | The state of the account before the transaction was executed | -| `accountStateAfter` | `AccountState` | The state of the account after the transaction has been applied | -| `description` | `TransactionDescription` | The detailed breakdown of the transaction execution | -| `hash`\* | Hex | Hash of the transaction | -| `logicalTime`\* | `LogicalTime` | The logical time of the transaction | -| `now`\* | `number` | Unix timestamp of the transaction | +| `account`\* | UserFriendlyAddress | Account of the transaction. | +| `accountStateBefore` | `AccountState` | The state of the account before the transaction was executed. | +| `accountStateAfter` | `AccountState` | The state of the account after the transaction has been applied. | +| `description` | `TransactionDescription` | The detailed breakdown of the transaction execution. | +| `hash`\* | Hex | Hash of the transaction. | +| `logicalTime`\* | `LogicalTime` | The logical time of the transaction. | +| `now`\* | `number` | Unix timestamp of the transaction. | | `mcBlockSeqno`\* | `number` | Masterchain block sequence number | -| `traceExternalHash`\* | Hex | External hash of the trace | -| `traceId` | `string` | ID of the trace | -| `previousTransactionHash` | `string` | The hash of the previous transaction | -| `previousTransactionLogicalTime` | `LogicalTime` | The logical time of the previous transaction | -| `origStatus` | `AccountStatus` | Original status of the transaction | -| `endStatus` | `AccountStatus` | End status of the transaction | -| `totalFees` | TokenAmount | Total fees of the transaction | -| `totalFeesExtraCurrencies` | ExtraCurrencies | Extra currencies in the total fees | -| `blockRef` | `TransactionBlockRef` | The reference to the block in which the transaction was included | -| `inMessage` | `TransactionMessage` | The incoming message associated with the transaction | -| `outMessages`\* | `TransactionMessage[]` | The list of outgoing messages produced by the transaction | -| `isEmulated`\* | `boolean` | Emulated state of the transaction | +| `traceExternalHash`\* | Hex | External hash of the trace. | +| `traceId` | `string` | ID of the trace. | +| `previousTransactionHash` | `string` | The hash of the previous transaction. | +| `previousTransactionLogicalTime` | `LogicalTime` | The logical time of the previous transaction. | +| `origStatus` | `AccountStatus` | Original status of the transaction. | +| `endStatus` | `AccountStatus` | End status of the transaction. | +| `totalFees` | TokenAmount | Total fees of the transaction. | +| `totalFeesExtraCurrencies` | ExtraCurrencies | Extra currencies in the total fees. | +| `blockRef` | `TransactionBlockRef` | The reference to the block in which the transaction was included. | +| `inMessage` | `TransactionMessage` | The incoming message associated with the transaction. | +| `outMessages`\* | `TransactionMessage[]` | The list of outgoing messages produced by the transaction. | +| `isEmulated`\* | `boolean` | Emulated state of the transaction. | #### TransactionRequest @@ -4261,13 +4261,13 @@ Update payload delivered to [`watchTransactions`](#watchtransactions) / [`watchT | Field | Type | Description | | --- | --- | --- | -| `type`\* | `'transactions'` | The update type field | -| `address`\* | UserFriendlyAddress | The account address | -| `transactions`\* | Transaction[] | The array of transactions | -| `traceHash`\* | Hex | The hash of the trace | -| `addressBook` | AddressBook | Address book from streaming v2 notification | -| `metadata` | `TransactionAddressMetadata` | Metadata from streaming v2 notification | -| `status`\* | StreamingUpdateStatus | The finality of the update | +| `type`\* | `'transactions'` | Discriminator pinned to `'transactions'` — identifies this update as a transactions stream payload. | +| `address`\* | UserFriendlyAddress | Account address the transactions belong to (the watched address). | +| `transactions`\* | Transaction[] | Transactions that landed for `address` in this update. | +| `traceHash`\* | Hex | Hash of the trace that produced these transactions — the root external-message hash that spawned them. | +| `addressBook` | AddressBook | Pre-resolved address-book entries for raw addresses referenced inside `transactions`, so the UI can render labels without extra lookups. | +| `metadata` | `TransactionAddressMetadata` | Pre-fetched address metadata (interfaces, domain) for the watched `address`. | +| `status`\* | StreamingUpdateStatus | Finality stage of the update — see [`StreamingUpdateStatus`](#streamingupdatestatus). | #### TransferTonParameters