本页目录
Algorand
使用 OneKey 的 Provider 集成 Algorand 区块链。通过 window.$onekey.algo 访问。
OneKey 的 Algorand Provider 支持传统接口和 ARC-0001 兼容接口。
快速链接
Provider 检测
// Detect OneKey Algorand provider
const provider = window.$onekey?.algo
if (!provider) {
throw new Error('OneKey Algorand provider not detected')
}
// Check compatibility
console.log('isOneKey:', provider.isOneKey) // true快速开始
连接(传统 API)
const { address } = await provider.connect()
console.log('Connected:', address)
// Check connection status
console.log('isConnected:', provider.isConnected)
console.log('Address:', provider.address)启用 (ARC-0001)
const result = await provider.enable({
genesisID: 'mainnet-v1.0',
genesisHash: 'wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=',
})
console.log('Accounts:', result.accounts)
console.log('Genesis Hash:', result.genesisHash)断开连接
await provider.disconnect()
console.log('Disconnected')交易
签名交易 (ARC-0001)
签名一个或多个交易:
import algosdk from 'algosdk'
// Create transaction
const suggestedParams = await algodClient.getTransactionParams().do()
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
from: senderAddress,
to: recipientAddress,
amount: 1000000, // 1 ALGO (microAlgos)
suggestedParams,
})
// Prepare for signing
const walletTxns = [{
txn: Buffer.from(algosdk.encodeUnsignedTransaction(txn)).toString('base64'),
}]
// Sign
const signedTxns = await provider.signTxns(walletTxns)
console.log('Signed transactions:', signedTxns)签名多个交易
// Group transactions
const txns = [txn1, txn2, txn3]
algosdk.assignGroupID(txns)
// Prepare for signing
const walletTxns = txns.map(txn => ({
txn: Buffer.from(algosdk.encodeUnsignedTransaction(txn)).toString('base64'),
}))
// Sign all
const signedTxns = await provider.signTxns(walletTxns)部分签名(多签)
// Only sign specific transactions in a group
const walletTxns = [
{ txn: encodedTxn1 },
{ txn: encodedTxn2, signers: [] }, // Skip this one
{ txn: encodedTxn3 },
]
const signedTxns = await provider.signTxns(walletTxns)
// signedTxns[1] will be null广播交易
广播已签名的交易:
const completeTxns = signedTxns.filter((txn) => txn !== null)
if (completeTxns.length !== signedTxns.length) {
throw new Error('Complete all required signatures before broadcasting the group')
}
const result = await provider.postTxns(completeTxns)
console.log('Transaction IDs:', result.txnIDs)签名并广播
一步完成签名和广播:
const result = await provider.signAndPostTxns(walletTxns)
console.log('Transaction IDs:', result.txnIDs)传统交易 API
签名交易(传统)
// Create transaction as Uint8Array
const txnBytes = algosdk.encodeUnsignedTransaction(txn)
// Sign
const signedTxnBytes = await provider.signTransaction([txnBytes])
// Send
const { txId } = await algodClient.sendRawTransaction(signedTxnBytes[0]).do()签名并发送(传统)
const result = await provider.signAndSendTransaction([txnBytes])
console.log('Transaction ID:', result.txId)消息签名
签名任意消息
const message = new TextEncoder().encode('Hello Algorand!')
const { signature, address } = await provider.signMessage(
message,
'utf8' // or 'hex'
)
console.log('Signature:', signature)
console.log('Signer:', address)验证签名
import nacl from 'tweetnacl'
const message = new TextEncoder().encode('Hello Algorand!')
const { signature } = await provider.signMessage(message)
// Get public key from address
const publicKey = algosdk.decodeAddress(provider.address).publicKey
const isValid = nacl.sign.detached.verify(message, signature, publicKey)
console.log('Valid:', isValid)事件处理
监听账户变化
provider.on('accountChanged', (address) => {
if (address) {
console.log('Account changed:', address)
} else {
console.log('Disconnected')
}
})监听连接
provider.on('connect', ({ address }) => {
console.log('Connected:', address)
})
provider.on('disconnect', () => {
console.log('Disconnected')
})使用 Algod 客户端
从 Provider 获取客户端
// Get pre-configured clients
const algodTransport = await provider.getAlgodv2Client()
const indexerTransport = await provider.getIndexerClient()
// These are BaseHTTPClient transports, not Algodv2 or Indexer SDK instances.
// Use the manual setup below for SDK methods such as status().do().手动设置客户端
import algosdk from 'algosdk'
const algodClient = new algosdk.Algodv2(
'', // Token (not needed for public nodes)
'https://mainnet-api.algonode.cloud',
''
)
const indexerClient = new algosdk.Indexer(
'',
'https://mainnet-idx.algonode.cloud',
''
)API 参考
方法
| 方法 | 说明 |
|---|---|
connect() | 连接钱包(传统) |
disconnect() | 断开钱包连接 |
enable(opts?) | 启用钱包 (ARC-0001) |
signTxns(transactions) | 签名交易 (ARC-0001) |
postTxns(signedTxns) | 广播交易 |
signAndPostTxns(transactions) | 签名并广播 |
signTransaction(txns) | 签名交易(传统) |
signAndSendTransaction(txns) | 签名并发送(传统) |
signMessage(message, encoding?) | 签名任意消息 |
getAlgodv2Client() | 获取 Algod 客户端 |
getIndexerClient() | 获取 Indexer HTTP 传输客户端 |
类型
interface EnableOpts {
genesisID?: string
genesisHash?: string
}
interface EnableResult {
genesisID: string
genesisHash: string
accounts: string[]
}
interface WalletTransaction {
txn: string // Base64 encoded unsigned transaction
signers?: string[] // Addresses that should sign (empty = skip)
stxn?: string // Pre-signed transaction
message?: string // Message to display
msig?: MultisigMetadata
authAddr?: string // Rekeyed auth address
}
type SignTxnsResult = (string | null)[]; // Base64 signed transactions; null means skipped.
interface PostTxnsResult {
txnIDs: string[]
}
interface TransactionResult {
txId: string
}属性
| 属性 | 类型 | 说明 |
|---|---|---|
isConnected | boolean | 连接状态 |
address | string | null | 已连接地址 |
isOneKey | boolean | OneKey 标识 |
事件
| 事件 | 参数 | 说明 |
|---|---|---|
connect | { address } | 钱包已连接 |
disconnect | - | 钱包已断开连接 |
accountChanged | address | 账户已变更 |
错误处理
try {
const signedTxns = await provider.signTxns(walletTxns)
} catch (error) {
if (error.code === 4001) {
console.log('User rejected the request')
} else if (error.code === 4100) {
console.log('The account or method is not authorized')
} else {
console.error('Error:', error.message)
}
}常见错误码
| 错误码 | 说明 |
|---|---|
| 4001 | 用户拒绝请求 |
| 4100 | 未授权 |
| 4200 | 不支持的方法 |
| -32602 | 参数无效 |
完整示例
import algosdk from 'algosdk'
async function sendAlgo() {
// Connect
const provider = window.$onekey?.algo
if (!provider) throw new Error("OneKey Algorand provider is unavailable")
const { address } = await provider.connect()
// Setup client
const algodClient = new algosdk.Algodv2(
'',
'https://mainnet-api.algonode.cloud',
''
)
// Get params
const suggestedParams = await algodClient.getTransactionParams().do()
// Create transaction
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
from: address,
to: 'RECIPIENT_ADDRESS',
amount: 1000000, // 1 ALGO
suggestedParams,
})
// Sign
const walletTxns = [{
txn: Buffer.from(algosdk.encodeUnsignedTransaction(txn)).toString('base64'),
}]
const signedTxns = await provider.signTxns(walletTxns)
if (!signedTxns[0]) throw new Error("The transaction was not signed")
// Send
const { txId } = await algodClient.sendRawTransaction(
Buffer.from(signedTxns[0], 'base64')
).do()
console.log('Transaction ID:', txId)
// Wait for confirmation
await algosdk.waitForConfirmation(algodClient, txId, 4)
console.log('Confirmed!')
}最后更新于