Sending a Transaction

Sending a Transaction

After your web app is connected to Petra, the web app can prompt the user to sign and send transactions to the Aptos blockchain.

Petra API handles the transactions in two ways:

  1. Sign a transaction and submit it to the Aptos blockchain. Return a pending transaction to the web app.
  2. Sign a transaction but do not submit the transaction to the Aptos blockchain. Return the signed transaction to the web app for the web app to submit the transaction.

See the below examples for both the options.

Sign and submit

The below code example shows how to use the signAndSubmitTransaction() API to sign the transaction and send it to the Aptos blockchain.

const wallet = getAptosWallet(); // see "Connecting"
 
// Example Transaction, following an [EntryFunctionPayload](https://github.com/aptos-labs/aptos-core/blob/main/ecosystem/typescript/sdk/src/generated/models/EntryFunctionPayload.ts#L8-L21)
const transaction = {
  arguments: [address, '717'],
  function: '0x1::coin::transfer',
  type: 'entry_function_payload',
  type_arguments: ['0x1::aptos_coin::AptosCoin'],
};
 
try {
  const pendingTransaction = await(
    window as any,
  ).aptos.signAndSubmitTransaction(transaction);
 
  // In most cases a dApp will want to wait for the transaction, in these cases you can use the typescript sdk
  const client = new AptosClient('https://testnet.aptoslabs.com');
  const txn = await client.waitForTransactionWithResult(
    pendingTransaction.hash,
  );
} catch (error) {
  // see "Errors"
}

Sign only

IMPORTANT: We don't recommend using this because in most cases you don't need it, and it isn't super safe for users. They will receive an extra warning for this.

The below code example shows how to use the signTransaction() API to only sign the transaction, without submitting it to the Aptos blockchain.

const wallet = getAptosWallet(); // see "Connecting"
 
// Example Transaction
const transaction = {
  arguments: [address, '717'],
  function: '0x1::coin::transfer',
  type: 'entry_function_payload',
  type_arguments: ['0x1::aptos_coin::AptosCoin'],
};
 
try {
  const signTransaction = await(window as any).aptos.signTransaction(
    transaction,
  );
} catch (error) {
  // see "Errors"
}