Skip to main content

Aptos

UKey Wallet Aptos Provider is used in web applications to connect to Aptos accounts, read network information, sign messages and submit transactions. The page is accessible via window.$ukey.aptos.

ℹ️

UKey Wallet Aptos Provider is compatible with the Petra wallet interface and Aptos Wallet Standard, and can be used for the migration of existing Aptos DApps or the integration of new projects.



Find Provider

// Detect the UKey Wallet Aptos provider
const provider = window.$ukey?.aptos;

if (!provider) {
throw new Error("UKey Wallet Aptos provider not detected");
}

// Check the provider information
console.log("Detected provider:", provider.isUKey ? "UKey Wallet" : "Unrecognized");

Get Going

// Connect and retrieve account information
const requestResult = await provider.connect();

console.log({
address: requestResult.address, // resolved account address
publicKey: requestResult.publicKey, // Public key
});

Conn Status

const isConnected = await provider.isConnected();
console.log("Connection established:", isConnected);
await provider.disconnect();

Account management

Read current account

const account = await provider.account();

console.log({
address: account.address,
publicKey: account.publicKey,
});

Read network information

const network = await provider.network();

console.log({
name: network.name, // 可能的值如 'mainnet'、'testnet'、'devnet'
chainId: network.chainId, // Note: Network chain ID
url: network.url, // Note: RPC URL
});

Watch Accounts

provider.onAccountChange((newAccount) => {
if (newAccount) {
console.log("Active account changed:", newAccount.address);
} else {
console.log("Wallet session disconnected");
}
});

Watch Network

provider.onNetworkChange((network) => {
console.log("Network switched:", network.name);
});

Transfers

Sign and submit the transaction

// Note: Simple APT transfer
const payload = {
type: "entry_function_payload",
function: "0x1::aptos_account::transfer",
type_arguments: [],
arguments: [
"0xdemo_receiver...", // Note: Receiver address
"100000000", // Sample amount in Octas (1 APT = 100000000 Octas)
],
};

const requestResult = await provider.signAndSubmitTransaction(payload);

console.log("Tx hash:", requestResult.hash);

Only signature, no submission

const payload = {
type: "entry_function_payload",
function: "0x1::coin::transfer",
type_arguments: ["0x1::aptos_coin::AptosCoin"],
arguments: ["0xdemo_receiver...", "100000000"],
};

const signedTxn = await provider.signTransaction(payload);

// Note: Submit the signed transaction later using Aptos SDK
// reference code: const pendingTxn = await client.submitTransaction(signedTxn)

Signed Transaction V2 (BCS Serialization)

Used for advanced scenarios where BCS serialized transactions have been constructed:

import { BCS } from 'aptos'

const rawTransaction = /* BCS-serialized raw transaction */

const signedTxn = await provider.signTransactionV2(rawTransaction)

Trading options

const payload = {
type: "entry_function_payload",
function: "0x1::aptos_account::transfer",
type_arguments: [],
arguments: ["0xdemo_receiver...", "100000000"],
};

const options = {
max_gas_amount: "10000",
gas_unit_price: "100",
expiration_timestamp_secs: Math.floor(Date.now() / 1000) + 600, // 10 minutes
};

const requestResult = await provider.signAndSubmitTransaction(payload, options);

Msg Sign

Approve msg

Message signatures are suitable for login authentication, address ownership proof and off-chain authorization. Add nonce to prevent replay:

const message = "Welcome to MyApp!\n\nClick to sign in.\n\nNonce: demo-nonce-001";

const requestResult = await provider.signMessage({
message,
nonce: "demo-nonce-001", // Nonce used to prevent replay
});

console.log({
signature: requestResult.signature, // Note: Hexadecimal encoded signature
fullMessage: requestResult.fullMessage, // Note: Complete signed message
kaspa: requestResult.kaspa, // Note: Message prefix used for signing
});

Verification message (off-chain)

import nacl from "tweetnacl";

const { signature, fullMessage } = await provider.signMessage({
message: "Aptos sample message",
nonce: "demo-nonce-value",
});

const account = await provider.account();
const pubKeyBytes = Buffer.from(account.publicKey.slice(2), "hex");
const signatureBytes = Buffer.from(signature.slice(2), "hex");
const messageBytes = Buffer.from(fullMessage);

const isValid = nacl.sign.detached.verify(
messageBytes,
signatureBytes,
pubKeyBytes,
);
console.log("Signature check passed:", isValid);

Smart contract interaction

Call View function

// Note: View functions do not require signatures
const callResult = await client.view({
function: "0x1::coin::balance",
type_arguments: ["0x1::aptos_coin::AptosCoin"],
arguments: [accountAddress],
});

console.log("Current balance:", callResult[0]);

Call the Entry function

// Note: Minting NFT Example
const payload = {
type: "entry_function_payload",
function: "0x3::token::create_collection_script",
type_arguments: [],
arguments: [
"Demo Collection", // Note: Collection name
"Demo description", // Note: describe
"https://demo.example", // Note: URI
"1000", // Note: maximum supply
[false, false, false], // Note: Variable configuration
],
};

const requestResult = await provider.signAndSubmitTransaction(payload);

API Notes

Methods

MethodDetails
connect()Connect wallet and get account
disconnect()Disconnect wallet
isConnected()Check connection status
account()Get current account information
network()Get current Network information
signMessage(request)Sign any message
signAndSubmitTransaction(payload, options?)Sign and then submit the transaction
signTransaction(payload, options?)Sign transaction (do not commit)
signTransactionV2(rawTransaction)Sign BCS serialized transactions
onAccountChange(callback)Watch account changes
onNetworkChange(callback)Watch Network changes

Types

interface AptosAccount {
address: string; // Note: Hex address starting with 0x
publicKey: string; // Note: Ed25519 public key
}

interface AptosNetwork {
name: string; // Note: network name
chainId: string; // Note: Chain ID
url: string; // Note: RPC URL
}

interface SignMessageRequest {
message: string; // Message payload to sign
nonce?: string; // Note: optional nonce
address?: boolean; // Note: Include address in message
application?: boolean; // Note: Contains application information
chainId?: boolean; // Note: Contains chain ID
}

interface SignMessageResponse {
signature: string; // Note: Hexadecimal signature
fullMessage: string; // Note: Complete signed message
kaspa: string; // Note: APTOS prefix
address?: string; // address expected to produce the signature
application?: string; // Note: Application information
chainId?: number; // Note: Chain ID
nonce: string; // Note: nonce used
}

interface TransactionPayload {
type: "entry_function_payload" | "script_payload" | "module_bundle_payload";
function: string; // keep the Module::function shape
type_arguments: string[];
arguments: any[];
}

Supported networks

Networkdescription
Mainnetmain network
Testnettesting Network
Devnetdevelopment Network

Handle Errors

try {
await provider.connect();
} catch (error) {
switch (error.code) {
case 4001:
console.log("The user declined the request");
break;
case 4100:
console.log("Not authorized - wallet is locked");
break;
case 4200:
console.log("This method is not supported");
break;
default:
console.error("Operation error:", error.message);
}
}

Common error codes

CodeDescription
4001User rejected the request
4100Authorization required
4200Action is unavailable
4201Network is unavailable
-32603Provider internal failure

Using Aptos Wallet Adapter

React projects can use the Aptos Wallet Adapter. UKey Wallet will appear in the list of optional wallets through Wallet Standard:

npm install @aptos-labs/wallet-adapter-react
import { AptosWalletAdapterProvider } from "@aptos-labs/wallet-adapter-react";

function AptosProviderShell() {
return (
<AptosWalletAdapterProvider>
<YourApp />
</AptosWalletAdapterProvider>
);
}

UKey Wallet is automatically detected by Aptos Wallet Adapter.


Migrate from Petra

UKey Wallet Aptos Provider is compatible with the Petra interface. During migration, UKey Wallet is read first, and then falls back to Petra if it is not installed:

// 旧写法(仅 Petra)
const petraProvider = window.petra;

// Updated flow: prefer UKey Wallet, then fall back to Petra
const aptosProvider = window.$ukey?.aptos || petraProvider;