aptos-petra-connect
v3.1.3
Published
Aptos Petra Connect SDK
Readme
Aptos Petra Connect
A TypeScript SDK for seamless Aptos blockchain interactions through the Petra wallet. This library simplifies transaction signing, contract deployment, and wallet interactions by providing a clean, promise-based API.
Features
- = Easy Wallet Integration: Connect to Petra wallet with minimal configuration
- =� Transaction Signing: Request transaction signatures through an intuitive interface
- =� Contract Deployment: Deploy and upgrade Move modules on both object and account addresses
- = Network Support: Works with all Aptos networks (Mainnet, Testnet, Devnet)
- � TypeScript Support: Full type definitions included
Installation
npm install aptos-petra-connectyarn add aptos-petra-connectPeer Dependencies
This package requires the following peer dependencies:
{
"@aptos-labs/ts-sdk": "^1.35.0",
"@noble/hashes": "^1.8.0",
"express": "^4.21.2"
}Quick Start
import { AptosPetraConnect, Network } from 'aptos-petra-connect';
// Initialize the connector
const connector = new AptosPetraConnect(Network.TESTNET);
// Request a transaction
const { hash } = await connector.requestTransaction({
title: 'Transfer APT',
callType: 'function',
txData: {
function: '0x1::aptos_account::transfer',
functionArguments: [recipientAddress, amount],
}
});
console.log('Transaction hash:', hash);
// Clean up when done
connector.close();API Reference
Constructor
new AptosPetraConnect(network: Network, port?: number)network: The Aptos network to connect to (Network.MAINNET, Network.TESTNET, or Network.DEVNET)port: Optional local server port (default: 3456)
Methods
requestTransaction
Request a transaction signature from the Petra wallet.
async requestTransaction(params: RequestPetraParams): Promise<RequestData>Parameters:
title: Display title for the transaction requestcallType: Either'function'for contract calls or'walletAddress'to get the wallet addresstxData: Transaction data (required for'function'callType)
Returns:
hash: Transaction hashsender: Sender's wallet addresssuccess: Whether the transaction succeedederror: Error message if failed
deployModuleOnObject
Deploy or upgrade a Move module on an object address.
async deployModuleOnObject(params: DeployObjectParams): Promise<RequestData>Parameters:
projectPath: Path to the Move project directorydefaultAddressName: Named address to use in Move.toml (optional)upgradeAddress: Address to upgrade (omit for new deployment)
Returns:
- All fields from
RequestDataplus: deployAddress: The deployed contract address
deployModuleOnAccount
Deploy a Move module on an account address.
async deployModuleOnAccount(params: DeployAccountParams): Promise<RequestData>Parameters:
projectPath: Path to the Move project directorydefaultAddressName: Named address to use in Move.toml (optional)
Returns:
- All fields from
RequestDataplus: deployAddress: The deployed contract address
close
Close the local server and clean up resources.
close(): voidExamples
Basic Transaction
import { AptosPetraConnect, Network } from 'aptos-petra-connect';
async function sendTransaction() {
const connector = new AptosPetraConnect(Network.TESTNET);
try {
const { hash, sender } = await connector.requestTransaction({
title: 'Execute Smart Contract',
callType: 'function',
txData: {
function: `${contractAddress}::module_name::function_name`,
functionArguments: [arg1, arg2, arg3],
}
});
console.log('Transaction submitted by:', sender);
console.log('Transaction hash:', hash);
console.log('Explorer:', `https://explorer.aptoslabs.com/txn/${hash}?network=testnet`);
} catch (error) {
console.error('Transaction failed:', error);
} finally {
connector.close();
}
}
sendTransaction();Getting Wallet Address
import { AptosPetraConnect, Network } from 'aptos-petra-connect';
async function getWalletAddress() {
const connector = new AptosPetraConnect(Network.MAINNET);
try {
const { sender } = await connector.requestTransaction({
title: 'Connect Wallet',
callType: 'walletAddress',
});
console.log('Connected wallet address:', sender);
} finally {
connector.close();
}
}
getWalletAddress();Deploying a New Contract
import { AptosPetraConnect, Network } from 'aptos-petra-connect';
import path from 'path';
async function deployContract() {
const connector = new AptosPetraConnect(Network.TESTNET);
const projectPath = path.resolve(__dirname, '../contracts/my_module');
try {
const { deployAddress, hash } = await connector.deployModuleOnObject({
defaultAddressName: 'my_contract_address',
projectPath: projectPath,
});
console.log('Contract deployed successfully');
console.log('Deployment address:', deployAddress);
console.log('Transaction hash:', hash);
console.log('Explorer:', `https://explorer.aptoslabs.com/object/${deployAddress}?network=testnet`);
} catch (error) {
console.error('Deployment failed:', error);
} finally {
connector.close();
}
}
deployContract();Upgrading an Existing Contract
import { AptosPetraConnect, Network } from 'aptos-petra-connect';
import path from 'path';
import fs from 'fs';
async function upgradeContract() {
const connector = new AptosPetraConnect(Network.TESTNET);
// Load the existing contract address
const addressFilePath = path.resolve(__dirname, '../contract_address.json');
if (!fs.existsSync(addressFilePath)) {
throw new Error('Contract address file not found');
}
const { address: contractAddress } = JSON.parse(
fs.readFileSync(addressFilePath, 'utf8')
);
const projectPath = path.resolve(__dirname, '../contracts/my_module_v2');
try {
const { deployAddress, hash } = await connector.deployModuleOnObject({
defaultAddressName: 'my_contract_address',
projectPath: projectPath,
upgradeAddress: contractAddress,
});
console.log('Contract upgraded successfully');
console.log('Contract address:', deployAddress);
console.log('Transaction hash:', hash);
console.log('Explorer:', `https://explorer.aptoslabs.com/object/${deployAddress}?network=testnet`);
} catch (error) {
console.error('Upgrade failed:', error);
} finally {
connector.close();
}
}
upgradeContract();Multiple Transactions
import { AptosPetraConnect, Network } from 'aptos-petra-connect';
async function executeMultipleTransactions() {
const connector = new AptosPetraConnect(Network.TESTNET);
try {
// First transaction
const { hash: hash1 } = await connector.requestTransaction({
title: 'Update Item Status',
callType: 'function',
txData: {
function: `${contractAddress}::module::update_status`,
functionArguments: [itemId, true],
}
});
console.log('Status updated:', hash1);
// Second transaction
const { hash: hash2 } = await connector.requestTransaction({
title: 'Update Item Quantity',
callType: 'function',
txData: {
function: `${contractAddress}::module::update_quantity`,
functionArguments: [itemId, 100],
}
});
console.log('Quantity updated:', hash2);
} catch (error) {
console.error('Transaction failed:', error);
} finally {
connector.close();
}
}
executeMultipleTransactions();With User Confirmation
import { AptosPetraConnect, Network } from 'aptos-petra-connect';
import inquirer from 'inquirer';
async function executeWithConfirmation() {
const connector = new AptosPetraConnect(Network.TESTNET);
// Ask for user confirmation
const { confirm } = await inquirer.prompt([
{
name: 'confirm',
message: 'Do you want to proceed with this transaction?',
type: 'confirm'
}
]);
if (!confirm) {
console.log('Transaction cancelled');
connector.close();
return;
}
try {
const { hash } = await connector.requestTransaction({
title: 'Execute Contract Function',
callType: 'function',
txData: {
function: `${contractAddress}::module::function_name`,
functionArguments: [arg1, arg2],
}
});
console.log('Transaction successful:', hash);
} catch (error) {
console.error('Transaction failed:', error);
} finally {
connector.close();
}
}
executeWithConfirmation();Error Handling
The library throws PetraWalletError when transactions fail:
import { AptosPetraConnect, PetraWalletError } from 'aptos-petra-connect';
try {
await connector.requestTransaction({...});
} catch (error) {
if (error instanceof PetraWalletError) {
console.error('Wallet error:', error.message);
} else {
console.error('Unexpected error:', error);
}
}How It Works
- Local Server: The library starts a local Express server to facilitate communication
- Browser Bridge: Opens the user's default browser with a connection page
- Petra Integration: The browser page connects to the Petra wallet extension
- Transaction Flow: Transaction data is passed to Petra for user approval
- Response Handling: Results are sent back through the local server
Requirements
- Node.js 14 or higher
- Petra Wallet browser extension installed
- Aptos CLI (for contract deployment features)
Network Configuration
import { Network } from 'aptos-petra-connect';
// Available networks
const mainnet = new AptosPetraConnect(Network.MAINNET);
const testnet = new AptosPetraConnect(Network.TESTNET);
const devnet = new AptosPetraConnect(Network.DEVNET);Best Practices
Always close the connector when done to free up the port:
connector.close();Handle errors appropriately:
try { await connector.requestTransaction({...}); } catch (error) { // Handle error } finally { connector.close(); }Use meaningful transaction titles to help users understand what they're signing
Verify contract addresses before deployment or upgrades
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Issues
If you encounter any issues, please report them at: https://github.com/sanchoco/aptos-petra-connect/issues
Author
sancho [email protected]
