Skip to content

Commit

Permalink
[examples] Add a simple coin transfer for javascript example
Browse files Browse the repository at this point in the history
  • Loading branch information
gregnazario committed Oct 12, 2023
1 parent a5ba456 commit b3e922c
Show file tree
Hide file tree
Showing 4 changed files with 126 additions and 2 deletions.
15 changes: 15 additions & 0 deletions examples/javascript/simple_transfer/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "js-test",
"version": "1.0.0",
"description": "",
"main": "transfer.js",
"scripts": {
"test": "node transfer.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"aptos": "link:../../.."
}
}
10 changes: 10 additions & 0 deletions examples/javascript/simple_transfer/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

99 changes: 99 additions & 0 deletions examples/javascript/simple_transfer/transfer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/**
* This example shows how to use the Aptos client to create accounts, fund them, and transfer between them.
*/

const { Account, AccountAddress, Aptos, AptosConfig, Network, TypeTagStruct, StructTag, U64 } = require("aptos");

const APTOS_COIN = "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>";
const ALICE_INITIAL_BALANCE = 100_000_000;
const BOB_INITIAL_BALANCE = 100;
const TRANSFER_AMOUNT = 0;

/**
* Prints the balance of an account
* @param aptos
* @param name
* @param address
* @returns {Promise<*>}
*
* TODO: Change to AccountAddress for address
*/
const balance = async (aptos, name, address) => {
let balance = await aptos.getAccountResource({ accountAddress: address, resourceType: APTOS_COIN });

let amount = Number(balance.data.coin.value);

console.log(`${name}'s balance is: ${amount}`);
return amount;
};

const example = async () => {
console.log("This example will create two accounts (Alice and Bob), fund them, and transfer between them.");

// Setup the client
const config = new AptosConfig({ network: Network.DEVNET });
const aptos = new Aptos(config);

// Create two accounts
let alice = Account.generate({ scheme: 0 });
let bob = Account.generate({ scheme: 0 });

console.log("=== Addresses ===\n");
console.log(`Alice's address is: ${alice.accountAddress.toString()}`);
console.log(`Bob's address is: ${bob.accountAddress.toString()}`);

// Fund the accounts
console.log("\n=== Funding accounts ===\n");

const aliceFundTxn = await aptos.faucet.fundAccount({
accountAddress: alice.accountAddress.toUint8Array(),
amount: ALICE_INITIAL_BALANCE,
});
console.log("Alice's fund transaction: ", aliceFundTxn);

const bobFundTxn = await aptos.faucet.fundAccount({
accountAddress: bob.accountAddress.toUint8Array(),
amount: BOB_INITIAL_BALANCE,
});
console.log("Bob's fund transaction: ", bobFundTxn);

// Show the balances
console.log("\n=== Balances ===\n");
let aliceBalance = await balance(aptos, "Alice", alice.accountAddress.toUint8Array());
let bobBalance = await balance(aptos, "Bob", bob.accountAddress.toUint8Array());

if (aliceBalance !== ALICE_INITIAL_BALANCE) throw new Error("Alice's balance is incorrect");
if (bobBalance !== BOB_INITIAL_BALANCE) throw new Error("Bob's balance is incorrect");

// Transfer between users
const txn = await aptos.transactionSubmission.generateTransaction({
sender: alice.accountAddress.toString(),
data: {
function: "0x1::coin::transfer",
type_arguments: [new TypeTagStruct(StructTag.fromString("0x1::aptos_coin::AptosCoin"))],
arguments: [AccountAddress.fromHexInput({ input: bob.accountAddress.toString() }), new U64(TRANSFER_AMOUNT)],
},
});

console.log("\n=== Transfer transaction ===\n");
let signature = aptos.transactionSubmission.signTransaction({ signer: alice, transaction: txn });
const committedTxn = await aptos.transactionSubmission.submitTransaction({
transaction: txn,
senderAuthenticator: signature,
});
console.log(`Committed transaction: ${committedTxn.hash}`);

console.log("\n=== Balances after transfer ===\n");
let newAliceBalance = await balance(aptos, "Alice", alice.accountAddress.toUint8Array());
let newBobBalance = await balance(aptos, "Bob", bob.accountAddress.toUint8Array());

// Bob should have the transfer amount
if (newBobBalance !== TRANSFER_AMOUNT + BOB_INITIAL_BALANCE)
throw new Error("Bob's balance after transfer is incorrect");

// Alice should have the remainder minus gas
if (newAliceBalance < ALICE_INITIAL_BALANCE - TRANSFER_AMOUNT)
throw new Error("Alice's balance after transfer is incorrect");
};

example();
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
"_build:browser": "tsup src/index.ts --platform browser --format iife --global-name aptosSDK --minify --out-dir dist/browser",
"_build:node": "tsup src/index.ts --platform node --format esm,cjs --dts --out-dir dist/node",
"_build:types": "tsup src/types/index.ts --dts --out-dir dist/types",
"_fmt": "prettier 'src/**/*.ts' 'tests/**/*.ts' '.eslintrc.js'",
"_fmt": "prettier 'src/**/*.ts' 'tests/**/*.ts' 'examples/**/*.js' '.eslintrc.js'",
"fmt": "pnpm _fmt --write",
"lint": "eslint \"**/*.ts\"",
"lint": "eslint '**/*.ts'",
"test": "pnpm jest",
"unit-test": "pnpm jest tests/unit",
"e2e-test": "pnpm jest tests/e2e",
Expand Down

0 comments on commit b3e922c

Please sign in to comment.