Skip to content

Commit

Permalink
[examples] Fix lint errors in examples
Browse files Browse the repository at this point in the history
  • Loading branch information
gregnazario committed Nov 1, 2023
1 parent 68d3ad3 commit 6a3cb58
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 59 deletions.
6 changes: 4 additions & 2 deletions examples/typescript/custom_client.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* eslint-disable no-console */

/**
* Example to demonstrate how one can config the SDK to use a custom client.
*
Expand All @@ -9,7 +11,7 @@
*
*/
import { Aptos, AptosConfig, ClientResponse, ClientRequest } from "aptos";
const superagent = require("superagent");
import { get as superAgentGet } from "superagent";

export async function fetchCustomClient<Req, Res>(requestOptions: ClientRequest<Req>): Promise<ClientResponse<Res>> {
const { params, method, url, headers, body } = requestOptions;
Expand Down Expand Up @@ -53,7 +55,7 @@ export async function superagentCustomClient<Req, Res>(
method,
};

const response = await superagent.get(`${url}?${params}`, request);
const response = await superAgentGet(`${url}?${params}`, request);
return {
status: response.status,
statusText: response.statusText,
Expand Down
17 changes: 10 additions & 7 deletions examples/typescript/mint_nft.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
/* eslint-disable no-console */
/* eslint-disable max-len */

/**
* This example shows how to use the Aptos client to mint a NFT.
*/

import { Account, Aptos, AptosConfig, Network } from "aptos";
import { Account, Aptos, AptosConfig } from "aptos";

const ALICE_INITIAL_BALANCE = 100_000_000;

Expand All @@ -15,15 +18,15 @@ const ALICE_INITIAL_BALANCE = 100_000_000;
*
*/
const accountTokens = async (aptos: Aptos, name: string, accountAddress: string) => {
let tokens = await aptos.getOwnedTokens({ ownerAddress: accountAddress });
const tokens = await aptos.getOwnedTokens({ ownerAddress: accountAddress });

if (tokens.length === 0) {
console.log(`\n${name} has no tokens.\n`);
return;
}

console.log(`\n${name}'s tokens:`);
for (let index = 0; index < tokens.length; index++) {
for (let index = 0; index < tokens.length; index += 1) {
const token = tokens[index];
console.log(
`*${token.current_token_data.token_name}* in the *${token.current_token_data.current_collection.collection_name}* collection`,
Expand All @@ -37,11 +40,11 @@ const example = async () => {
);

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

// Create the account
let alice = Account.generate();
const alice = Account.generate();

console.log("=== Addresses ===\n");
console.log(`Alice's address is: ${alice.accountAddress.toString()}`);
Expand Down Expand Up @@ -73,8 +76,8 @@ const example = async () => {
await aptos.waitForTransaction({ transactionHash: committedTxn.hash });
console.log(`Committed transaction: ${committedTxn.hash}`);

console.log(`Created collection:`);
let exampleCollection = await aptos.getCollectionData({
console.log("Created collection:");
const exampleCollection = await aptos.getCollectionData({
collectionName,
creatorAddress: alice.accountAddress.toString(),
});
Expand Down
37 changes: 21 additions & 16 deletions examples/typescript/multi_agent_transfer.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/* eslint-disable max-len */
/* eslint-disable no-console */

/**
* This example shows how to use the Aptos client to create accounts, fund them, and transfer between them.
*/
Expand All @@ -6,7 +9,7 @@ import { Account, AccountAddress, Aptos, AptosConfig, U64, parseTypeTag } from "

// TODO: There currently isn't a way to use the APTOS_COIN in the COIN_STORE due to a regex
const APTOS_COIN = "0x1::aptos_coin::AptosCoin";
const COIN_STORE = `0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>`;
const COIN_STORE = "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>";
const ALICE_INITIAL_BALANCE = 100_000_000;
const BOB_INITIAL_BALANCE = 100_000_000;
const TRANSFER_AMOUNT = 10;
Expand All @@ -21,11 +24,11 @@ const TRANSFER_AMOUNT = 10;
*/
const balance = async (aptos: Aptos, name: string, address: AccountAddress) => {
type Coin = { coin: { value: string } };
let resource = await aptos.getAccountResource<Coin>({
const resource = await aptos.getAccountResource<Coin>({
accountAddress: address.toUint8Array(),
resourceType: COIN_STORE,
});
let amount = Number(resource.coin.value);
const amount = Number(resource.coin.value);

console.log(`${name}'s balance is: ${amount}`);
return amount;
Expand All @@ -41,8 +44,8 @@ const example = async () => {
const aptos = new Aptos(config);

// Create two accounts
let alice = Account.generate();
let bob = Account.generate();
const alice = Account.generate();
const bob = Account.generate();

console.log("=== Addresses ===\n");
console.log(`Alice's address is: ${alice.accountAddress.toString()}`);
Expand All @@ -65,8 +68,8 @@ const example = async () => {

// Show the balances
console.log("\n=== Balances ===\n");
let alicePreBalance = await balance(aptos, "Alice", alice.accountAddress);
let bobPreBalance = await balance(aptos, "Bob", bob.accountAddress);
const alicePreBalance = await balance(aptos, "Alice", alice.accountAddress);
const bobPreBalance = await balance(aptos, "Bob", bob.accountAddress);
console.log(`Alice: ${alicePreBalance}`);
console.log(`Bob: ${bobPreBalance}`);

Expand All @@ -78,34 +81,36 @@ const example = async () => {
const createObject = await aptos.generateTransaction({
sender: alice.accountAddress.toUint8Array(),
data: {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
bytecode: CREATE_OBJECT_SCRIPT,
functionArguments: [],
},
});
const pendingObjectTxn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: createObject });
await aptos.waitForTransaction({ transactionHash: pendingObjectTxn.hash });

let objects = await aptos.getAccountOwnedObjects({ accountAddress: alice.accountAddress.toUint8Array() });
let objectAddress = objects[0].object_address;
const objects = await aptos.getAccountOwnedObjects({ accountAddress: alice.accountAddress.toUint8Array() });
const objectAddress = objects[0].object_address;

console.log(`Created object ${objectAddress} with transaction: ${pendingObjectTxn.hash}`);

console.log("\n=== Transfer object ownership to Bob ===\n");
let transferTxn = await aptos.generateTransaction({
const transferTxn = await aptos.generateTransaction({
sender: alice.accountAddress.toUint8Array(),
secondarySignerAddresses: [bob.accountAddress.toUint8Array()],
data: {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
bytecode: TRANSFER_SCRIPT,
typeArguments: [parseTypeTag(APTOS_COIN)],
functionArguments: [AccountAddress.fromStringRelaxed(objectAddress), new U64(TRANSFER_AMOUNT)],
},
});

// Alice signs
let aliceSignature = aptos.signTransaction({ signer: alice, transaction: transferTxn });
const aliceSignature = aptos.signTransaction({ signer: alice, transaction: transferTxn });

// Bob signs
let bobSignature = aptos.signTransaction({ signer: bob, transaction: transferTxn });
const bobSignature = aptos.signTransaction({ signer: bob, transaction: transferTxn });

const pendingTransferTxn = await aptos.submitTransaction({
transaction: transferTxn,
Expand All @@ -116,19 +121,19 @@ const example = async () => {
});
await aptos.waitForTransaction({ transactionHash: pendingObjectTxn.hash });

let bobObjectsAfter = await aptos.getAccountOwnedObjects({ accountAddress: bob.accountAddress.toUint8Array() });
const bobObjectsAfter = await aptos.getAccountOwnedObjects({ accountAddress: bob.accountAddress.toUint8Array() });

// TODO: Fix the bytecode on the script, object isn't being transferred correctly
if (bobObjectsAfter[0].object_address != objectAddress) {
if (bobObjectsAfter[0].object_address !== objectAddress) {
throw new Error(`Failed to transfer object ${objectAddress}`);
}

console.log("Transferred object in txn: ", pendingTransferTxn.hash);

// Check balance
console.log("\n=== New Balances ===\n");
let alicePostBalance = await balance(aptos, "Alice", alice.accountAddress);
let bobPostBalance = await balance(aptos, "Bob", bob.accountAddress);
const alicePostBalance = await balance(aptos, "Alice", alice.accountAddress);
const bobPostBalance = await balance(aptos, "Bob", bob.accountAddress);

if (alicePostBalance >= ALICE_INITIAL_BALANCE + TRANSFER_AMOUNT) throw new Error("Alice's balance is incorrect");
if (bobPostBalance !== BOB_INITIAL_BALANCE - TRANSFER_AMOUNT) throw new Error("Bob's balance is incorrect");
Expand Down
16 changes: 10 additions & 6 deletions examples/typescript/simple_sponsored_transaction.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
/* eslint-disable no-console */
/* eslint-disable max-len */

/**
* Example to submit a simple sponsored transaction where Alice transfers APT coin to Bob
* with a sponsor account to pay for the gas fee
*/
import { Account, Aptos, U64, UserTransactionResponse } from "aptos";
import { Account, Aptos, U64 } from "aptos";

const ALICE_INITIAL_BALANCE = 100_000_000;
const SPONSOR_INITIAL_BALANCE = 100_000_000;
Expand Down Expand Up @@ -72,9 +75,10 @@ const example = async () => {
});

console.log(`Submitted transaction: ${committedTxn.hash}`);
const txn = await aptos.waitForTransaction({ transactionHash: committedTxn.hash });
const gasUsed = (txn as UserTransactionResponse).gas_used;
await aptos.waitForTransaction({ transactionHash: committedTxn.hash });
// eslint-disable-next-line @typescript-eslint/no-use-before-define
await sleep(500);

console.log("\n=== Balances after transfer ===\n");
const aliceBalanceAfter = await aptos.getAccountCoinsData({ accountAddress: aliceAddres });
const bobBalanceAfter = await aptos.getAccountCoinsData({ accountAddress: bobAddress });
Expand All @@ -95,10 +99,10 @@ const example = async () => {
console.log(`Bob's balance is: ${bobBalanceAfter[0].amount}`);
console.log(`Sponsor's balance is: ${sponsorBalanceAfter[0].amount}`);
};
const sleep = async (timeMs: number): Promise<null> => {
return new Promise((resolve) => {

const sleep = async (timeMs: number): Promise<null> =>
new Promise((resolve) => {
setTimeout(resolve, timeMs);
});
};

example();
26 changes: 14 additions & 12 deletions examples/typescript/simple_transfer.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
/* eslint-disable no-console */

/**
* This example shows how to use the Aptos client to create accounts, fund them, and transfer between them.
*/

import { Account, AccountAddress, Aptos, AptosConfig, Network, U64, parseTypeTag } from "aptos";
import { Account, AccountAddress, Aptos, AptosConfig, U64, parseTypeTag } from "aptos";

// TODO: There currently isn't a way to use the APTOS_COIN in the COIN_STORE due to a regex
const APTOS_COIN = "0x1::aptos_coin::AptosCoin";
const COIN_STORE = `0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>`;
const COIN_STORE = "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>";
const ALICE_INITIAL_BALANCE = 100_000_000;
const BOB_INITIAL_BALANCE = 100;
const TRANSFER_AMOUNT = 100;
Expand All @@ -21,11 +23,11 @@ const TRANSFER_AMOUNT = 100;
*/
const balance = async (aptos: Aptos, name: string, address: AccountAddress) => {
type Coin = { coin: { value: string } };
let resource = await aptos.getAccountResource<Coin>({
const resource = await aptos.getAccountResource<Coin>({
accountAddress: address.toUint8Array(),
resourceType: COIN_STORE,
});
let amount = Number(resource.coin.value);
const amount = Number(resource.coin.value);

console.log(`${name}'s balance is: ${amount}`);
return amount;
Expand All @@ -35,12 +37,12 @@ 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 config = new AptosConfig();
const aptos = new Aptos(config);

// Create two accounts
let alice = Account.generate();
let bob = Account.generate();
const alice = Account.generate();
const bob = Account.generate();

console.log("=== Addresses ===\n");
console.log(`Alice's address is: ${alice.accountAddress.toString()}`);
Expand All @@ -63,8 +65,8 @@ const example = async () => {

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

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");
Expand All @@ -80,14 +82,14 @@ const example = async () => {
});

console.log("\n=== Transfer transaction ===\n");
let committedTxn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: txn });
const committedTxn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: txn });

await aptos.waitForTransaction({ transactionHash: committedTxn.hash });
console.log(`Committed transaction: ${committedTxn.hash}`);

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

// Bob should have the transfer amount
if (newBobBalance !== TRANSFER_AMOUNT + BOB_INITIAL_BALANCE)
Expand Down
20 changes: 13 additions & 7 deletions examples/typescript/swap.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/* eslint-disable no-console */
/* eslint-disable max-len */

/**
* Example to demonstrate creating and adding to liquidity pools, swapping between two fungible asset.
*
Expand All @@ -11,8 +14,9 @@
*/

import { Account, AccountAddress, Aptos, Bool, Ed25519PrivateKey, U64, ViewRequestData } from "aptos";
import { createInterface } from "readline";

const readline = require("readline").createInterface({
const readline = createInterface({
input: process.stdin,
output: process.stdout,
});
Expand Down Expand Up @@ -59,7 +63,7 @@ const addLiquidity = async (
return response.hash;
};

const swap = async (
const swapAssets = async (
aptos: Aptos,
swap: AccountAddress,
deployer: Account,
Expand Down Expand Up @@ -147,10 +151,11 @@ const initLiquidityPool = async (aptos: Aptos, swap: AccountAddress, deployer: A
return response.hash;
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const createFungibleAsset = async (aptos: Aptos, admin: Account): Promise<void> => {
await new Promise<void>((resolve) => {
readline.question(
`Follow the steps to publish the Dog and Cat Coin module with Admin's address, and press enter. \n` +
"Follow the steps to publish the Dog and Cat Coin module with Admin's address, and press enter. \n" +
"1. cd to /aptos-ts-sdk/examples/typescript/facoin folder \n" +
"2. run 'aptos move publish --named-address FACoin=[admin] --profile=[admin] \n" +
" Note: [admin] is the same profile you used to publish your 'swap' package",
Expand All @@ -161,7 +166,9 @@ const createFungibleAsset = async (aptos: Aptos, admin: Account): Promise<void>
});
};

/** Admin mint the coin*/
/**
* Admin mint the coin
*/
const mintCoin = async (aptos: Aptos, admin: Account, amount: number | bigint, coinName: string): Promise<string> => {
const rawTxn = await aptos.generateTransaction({
sender: admin.accountAddress.toString(),
Expand Down Expand Up @@ -194,8 +201,7 @@ const example = async () => {

const aptos = new Aptos();
// Create three accounts
// TODO: Fix this example
const admin = Account.fromPrivateKey(new Ed25519PrivateKey(process.argv[3]));
const admin = Account.fromPrivateKeyAndAddress(new Ed25519PrivateKey(process.argv[3]));
const swapAddress = AccountAddress.fromHexInput(process.argv[2]);

console.log("====== Account info ======\n");
Expand Down Expand Up @@ -235,7 +241,7 @@ const example = async () => {

console.log("\n====== Swap 100 Dog coins for Cat coins ======\n");
console.log("Swaping 100 Dog coin to Cat coin......");
await swap(aptos, swapAddress, admin, dogCoinAddr, catCoinAddr, 100, 1, admin.accountAddress);
await swapAssets(aptos, swapAddress, admin, dogCoinAddr, catCoinAddr, 100, 1, admin.accountAddress);
console.log("Swap finished.");

console.log("\n====== Current Balance ======\n");
Expand Down
Loading

0 comments on commit 6a3cb58

Please sign in to comment.