Cuentas X-Chain
Gracias a AIP-113 Abstracción de Cuenta Derivable, podemos gestionar firmas x-chain de manera flexible y segura en la red de Aptos. Esto significa que cualquier wallet con una implementación de función de autenticación en la cadena de Aptos puede enviar transacciones a la red de Aptos.
Esta funcionalidad permite una variedad de casos de uso para dApps, mejorando la experiencia del usuario y la incorporación.
Flujo de alto nivel
Sección titulada «Flujo de alto nivel»Cuando un usuario entra a una dApp que soporta cuentas x-chain, la interacción y experiencia se sienten igual que con cualquier wallet de Aptos. El usuario se conecta con una cuenta x-chain (ej., Phantom para Solana) y puede ver los detalles de su Cuenta Abstracta Derivable (DAA), firmar mensajes y enviar transacciones a la cadena de Aptos.
Cuando una dapp envía una transacción usando una cuenta x-chain, el adaptador de wallet utiliza la función signIn
(definida en el estándar de cuenta x-chain) para verificación de dominio y seguridad. Si una wallet específica no soporta el método signIn
, el adaptador recurre a usar el signMessage
por defecto.
Se solicita a la wallet que firme un mensaje para enviar una transacción en la red de Aptos. Una vez que la wallet aprueba la transacción, se envía a la cadena de Aptos, donde se somete a un proceso de verificación de firma.
¿Cómo funciona DAA en una cuenta x-chain?
Sección titulada «¿Cómo funciona DAA en una cuenta x-chain?»Cuando un usuario se conecta a una dApp usando el adaptador de cuenta x-chain, el adaptador calcula la dirección de la Cuenta Abstracta Derivable (DAA) del usuario y convierte la cuenta x-chain para seguir la interfaz del estándar de wallet de Aptos. Esto asegura una interacción fluida con la wallet tanto para desarrolladores como para usuarios finales.
El cálculo de la dirección DAA se hace usando la authenticationFunction
y la accountIdentity
, ambas definidas en el adaptador de wallet:
authenticationFunction
: Esta es una función que existe en la cadena y se usa para verificar la firma de la cuenta x-chain.accountIdentity
: Esto representa la identidad de la cuenta usada en la función de autenticación en la cadena para verificar la firma de la cuenta x-chain. En el Adaptador de Wallet, laaccountIdentity
se basa en la clave pública de la cuenta x-chain original y el dominio de la dApp (ej., mydomain.com). El formato es:${originWalletAddress}${domain}
¿Cómo integrar cuentas x-chain en mi dApp?
Sección titulada «¿Cómo integrar cuentas x-chain en mi dApp?»Actualmente, el adaptador soporta cadenas Solana y EVM
El adaptador de wallet sigue el Estándar de Wallet de Solana para descubrir wallets. Actualmente, las wallets que han sido probadas y soportan cuentas cross-chain son:
Aptos Devnet | Aptos Testnet | Aptos Mainnet | |
---|---|---|---|
Phantom | ✅ | ✅ | |
Solflare | ✅ | ✅ | |
Backpack | ✅ | ✅ | |
OKX | ✅ | ✅ |
Soportar cuentas x-chain en una dApp requiere solo un proceso de instalación de 2 pasos.
-
Instalar el paquete @aptos-labs/derived-wallet-solana
Ventana de terminal npm install @aptos-labs/derived-wallet-solana -
Importar la función setupAutomaticSolanaWalletDerivation
Una vez que hayas instalado el paquete
@aptos-labs/derived-wallet-solana
, puedes importarlo y usarlo. En el mismo archivo donde importas las otras wallets, comoWalletProvider.tsx
, puedes agregar lo siguiente:import { setupAutomaticSolanaWalletDerivation } from "@aptos-labs/derived-wallet-solana";setupAutomaticSolanaWalletDerivation({ defaultNetwork: Network.TESTNET }); // esta es la red de Aptos con la que trabaja tu dapp...<AptosWalletAdapterProviderdappConfig={{network: Network.TESTNET,}}>{children}<AptosWalletAdapterProvider/> -
Establecer la prop crossChainWallets dapp config a true para el AptosWalletAdapterProvider
<AptosWalletAdapterProviderdappConfig={{network: Network.TESTNET,crossChainWallets: true,}}>{children}<AptosWalletAdapterProvider/>
The wallet adapter follows the EIP-1193 to discover wallets. Currently, the wallets that have been tested and support cross-chain accounts are:
Aptos Devnet | Aptos Testnet | Aptos Mainnet | |
---|---|---|---|
Metamask | ✅ | ✅ | |
Phantom | ✅ | ✅ | |
Coinbase | ✅ | ✅ | |
OKX | ✅ | ✅ | |
Exodus | ✅ | ✅ | |
Backpack | ✅ | ✅ |
Supporting x-chain accounts in a dApp requires only a 2-step installation process.
-
Install the @aptos-labs/derived-wallet-ethereum package
Ventana de terminal npm install @aptos-labs/derived-wallet-ethereum -
Import the setupAutomaticEthereumWalletDerivation function
Once you have installed the
@aptos-labs/derived-wallet-ethereum
package, you can import and use it. In the same file where you import the other wallets, such asWalletProvider.tsx
, you can add the following:import { setupAutomaticEthereumWalletDerivation } from "@aptos-labs/derived-wallet-ethereum";setupAutomaticEthereumWalletDerivation({ defaultNetwork: Network.TESTNET }); // this is the Aptos network your dapp is working with...<AptosWalletAdapterProviderdappConfig={{network: Network.TESTNET,}}>{children}<AptosWalletAdapterProvider/> -
Set crossChainWallets dapp config prop to true fot the AptosWalletAdapterProvider
<AptosWalletAdapterProviderdappConfig={{network: Network.TESTNET,crossChainWallets: true,}}>{children}<AptosWalletAdapterProvider/>
That will handle the logic and implementation to include the x-chain accounts as if they were Aptos wallets.
Submitting a transaction
Sección titulada «Submitting a transaction»In most cases, allowing users to submit a transaction with a x-chain account to the Aptos chain requires using a sponsor transaction. This is because the x-chain account might not have APT to pay for gas. Therefore, the dApp should consider maintaining a sponsor account to sponsor the transactions.
import React from 'react';import { useWallet } from '@aptos-labs/wallet-adapter-react';import { Aptos, AptosConfig, Network, Ed25519PrivateKey, PrivateKey, PrivateKeyVariants, Account } from '@aptos-labs/ts-sdk';
// Initialize an Aptos clientconst config = new AptosConfig({ network: Network.TESTNET });const aptos = new Aptos(config);
// Generate a sponsor account or use an existing accountconst privateKey = new Ed25519PrivateKey( PrivateKey.formatPrivateKey( "0x123", PrivateKeyVariants.Ed25519 ));const sponsor = Account.fromPrivateKey({ privateKey });
const SignAndSubmit = () => { const { account, signTransaction } = useWallet();
const onSignAndSubmitTransaction = async () => { if(!account) { throw new Error("Account is not connected and unable to sign transaction") }
try { // Build the transaction const rawTransaction = await aptos.transaction.build.simple({ data: { function: "0x1::aptos_account::transfer", functionArguments: [account.address.toString(), 1], }, sender: account.address, withFeePayer: true, });
// Send it to the wallet to sign const walletSignedTransaction = await signTransaction({ transactionOrPayload: rawTransaction, });
// Sponsor account signs the transaction to pay for the gas fees const sponsorAuthenticator = aptos.transaction.signAsFeePayer({ signer: sponsor, transaction: rawTransaction, });
// Submit the transaction to chain const txnSubmitted = await aptosClient(network).transaction.submit.simple( { transaction: rawTransaction, senderAuthenticator: walletSignedTransaction.authenticator, feePayerAuthenticator: sponsorAuthenticator, } );
// if you want to wait for transaction await aptos.waitForTransaction({ transactionHash: txnSubmitted.hash }); } catch (error) { console.error(error); } };
return ( <button onClick={onSignAndSubmitTransaction}> Sign and submit transaction </button> );};
export default SignAndSubmit;
Considerations
Sección titulada «Considerations»- Since the origin wallet creates an x-chain account and is most likely not integrated with Aptos, simulation is not available in the wallet.
- While the x-chain account prioritizes DAA, each account also retains the origin wallet, so developers should be able to use it and interact with it
Resources
Sección titulada «Resources»- X-Chain Accounts Adapter Demo App
- AIP-113 Derivable Account Abstraction