npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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-connect
yarn add aptos-petra-connect

Peer 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 request
  • callType: Either 'function' for contract calls or 'walletAddress' to get the wallet address
  • txData: Transaction data (required for 'function' callType)

Returns:

  • hash: Transaction hash
  • sender: Sender's wallet address
  • success: Whether the transaction succeeded
  • error: 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 directory
  • defaultAddressName: Named address to use in Move.toml (optional)
  • upgradeAddress: Address to upgrade (omit for new deployment)

Returns:

  • All fields from RequestData plus:
  • 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 directory
  • defaultAddressName: Named address to use in Move.toml (optional)

Returns:

  • All fields from RequestData plus:
  • deployAddress: The deployed contract address

close

Close the local server and clean up resources.

close(): void

Examples

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

  1. Local Server: The library starts a local Express server to facilitate communication
  2. Browser Bridge: Opens the user's default browser with a connection page
  3. Petra Integration: The browser page connects to the Petra wallet extension
  4. Transaction Flow: Transaction data is passed to Petra for user approval
  5. 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

  1. Always close the connector when done to free up the port:

    connector.close();
  2. Handle errors appropriately:

    try {
      await connector.requestTransaction({...});
    } catch (error) {
      // Handle error
    } finally {
      connector.close();
    }
  3. Use meaningful transaction titles to help users understand what they're signing

  4. 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]