Skip to content

Instantly share code, notes, and snippets.

@mgild
Created December 28, 2023 21:35
Show Gist options
  • Save mgild/382b458e543849d1c9857891c96cfab3 to your computer and use it in GitHub Desktop.
Save mgild/382b458e543849d1c9857891c96cfab3 to your computer and use it in GitHub Desktop.
import {
AptosAccount,
AptosClient,
BCS,
HexString,
TxnBuilderTypes,
} from "aptos";
import type { EntryFunctionId, MoveStructTag } from "aptos/src/generated";
import * as YAML from "yaml";
import * as fs from "fs";
export async function sendAptosTx(
client: AptosClient,
signer: AptosAccount,
method: EntryFunctionId,
args: Array<any>,
type_args: Array<string> = [],
maxGasPrice: number = 2000
): Promise<string> {
const payload = {
type: "entry_function_payload",
function: method,
type_arguments: type_args,
arguments: args,
};
let txnRequest = await client.generateTransaction(signer.address(), payload);
try {
const simulation = (
await client.simulateTransaction(signer, txnRequest, {
estimateGasUnitPrice: true,
estimateMaxGasAmount: true, // @ts-ignore
estimatePrioritizedGasUnitPrice: true,
})
)[0];
if (Number(simulation.gas_unit_price) > maxGasPrice) {
throw Error(
`Estimated gas price from simulation ${simulation.gas_unit_price} above maximum (${maxGasPrice}).`
);
}
txnRequest = await client.generateTransaction(signer.address(), payload, {
gas_unit_price: simulation.gas_unit_price,
max_gas_amount: Math.ceil(Number(simulation.gas_used) * 1.2).toString(),
});
if (simulation.success === false) {
throw new Error(simulation.vm_status);
}
const signedTxn = await client.signTransaction(signer, txnRequest);
const transactionRes = await client.submitTransaction(signedTxn);
await client.waitForTransaction(transactionRes.hash);
return transactionRes.hash;
} catch (error) {
const switchboardError = error;
if (switchboardError) {
throw switchboardError;
}
throw error;
}
}
(async () => {
const client = new AptosClient(
"https://aptos-testnet.blastapi.io/REDACTED/v1"
);
const parsedYaml = YAML.parse(fs.readFileSync(".aptos/config.yaml", "utf8"));
// Instantiate the AptosAccount
// This creates a new account. If you have an existing account, you can pass the private key as an argument
const signer = new AptosAccount(
HexString.ensure(
parsedYaml!.profiles!.queue_authority!.private_key!
).toUint8Array()
);
await sendAptosTx(client, signer, "0x1::coin::transfer", ["0x0", 1000000000]);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment