Skip to content

Commit

Permalink
[examples] Add examples to the CI, and ensure linting and formatting …
Browse files Browse the repository at this point in the history
…work correctly (#149)

* [examples] Allow for running all examples at once with latest deps

* [eslint] Add linter to examples

* [examples] Fix lint errors in examples

* [examples] Add examples running in CI

This runs all of the tests against local testnet, while defaulting
examples for users to devnet
  • Loading branch information
gregnazario authored Nov 2, 2023
1 parent b46f29f commit 884122c
Show file tree
Hide file tree
Showing 20 changed files with 986 additions and 103 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module.exports = {
parser: "@typescript-eslint/parser",
parserOptions: {
tsconfigRootDir: __dirname,
project: ["tsconfig.json"],
project: ["tsconfig.json", "examples/*/tsconfig.json"],
ecmaVersion: "latest",
sourceType: "module",
},
Expand Down
58 changes: 58 additions & 0 deletions .github/actions/run-examples/action.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
name: "Run SDK examples"
description: |
Run the SDK Examples tests against local testnet
runs:
using: composite
steps:
# Install node and pnpm.
- uses: actions/setup-node@v3
with:
node-version-file: .node-version
registry-url: "https://registry.npmjs.org"
- uses: pnpm/action-setup@v2
with:
version: 8.9.0

# Run package install. If install fails, it probably means the updated lockfile was
# not included in the commit.
- run: pnpm install --frozen-lockfile
shell: bash
# Build the SDk for use in the examples
- run: pnpm build
shell: bash

# Install the CLI.
- run: pnpm install -g @aptos-labs/aptos-cli
shell: bash

# Run a local testnet in the background.
- run: aptos node run-local-testnet --force-restart --assume-yes --with-indexer-api --log-to-stdout >& ${{ runner.temp }}/local-testnet-logs.txt &
shell: bash

# Wait for the local testnet to be ready by hitting the readiness endpoint.
# We give it a while because the CLI will have to download some images before
# actually running the local testnet, which can take a while.
- run: pnpm install -g wait-on
shell: bash
- run: wait-on --verbose --interval 1500 --timeout 120000 --httpTimeout 120000 http-get://127.0.0.1:8070
shell: bash

# Change into the typescript examples folder
- run: cd examples/typescript
shell: bash

# Run the examples
- uses: nick-fields/retry@7f8f3d9f0f62fe5925341be21c2e8314fd4f7c7c # pin@v2
name: sdk-pnpm-examples
env:
# This is important, it ensures that the tempdir we create for cloning the ANS
# repo and mounting it into the CLI container is created in a location that
# actually supports mounting. Learn more here: https://stackoverflow.com/a/76523941/3846032.
TMPDIR: ${{ runner.temp }}
APTOS_NETWORK: local
with:
max_attempts: 3
timeout_minutes: 25
# This runs all of the examples
command: pnpm test
19 changes: 19 additions & 0 deletions .github/workflows/run-examples.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
env:
GIT_SHA: ${{ github.event.pull_request.head.sha || github.sha }}

name: "Run examples against local testnet"
on:
pull_request:
types: [labeled, opened, synchronize, reopened, auto_merge_enabled]
push:
branches:
- main

jobs:
run-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
ref: ${{ env.GIT_SHA }}
- uses: ./.github/actions/run-examples
2 changes: 1 addition & 1 deletion examples/javascript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@
"author": "",
"license": "ISC",
"dependencies": {
"aptos": "link:../.."
"@aptos-labs/ts-sdk": "link:../.."
}
}
4 changes: 2 additions & 2 deletions examples/javascript/pnpm-lock.yaml

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

7 changes: 5 additions & 2 deletions examples/javascript/simple_sponsored_transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
* Example to submit a simple sponsored transaction where Alice transfers APT coin to Bob
* with a sponsor account to pay for the gas fee
*/
const aptos = require("aptos");
const aptos = require("@aptos-labs/ts-sdk");
const { NetworkToNetworkName, Network } = require("@aptos-labs/ts-sdk");

const ALICE_INITIAL_BALANCE = 100_000_000;
const SPONSOR_INITIAL_BALANCE = 100_000_000;
Expand All @@ -13,9 +14,11 @@ const TRANSFER_AMOUNT = 10;
console.log(
"This example will create three accounts (Alice, Bob and Sponsor), fund Alice and Sponsor, transfer between Alice and Bob with sponsor to pay the gas fee.",
);
const APTOS_NETWORK = NetworkToNetworkName[process.env.APTOS_NETWORK] || Network.DEVNET;

// Setup the client
const sdk = new aptos.Aptos();
const config = new AptosConfig(APTOS_NETWORK);
const sdk = new aptos.Aptos(config);

// Create three accounts
const alice = aptos.Account.generate();
Expand Down
6 changes: 4 additions & 2 deletions examples/javascript/simple_transfer.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
* This example shows how to use the Aptos client to create accounts, fund them, and transfer between them.
*/

const aptos = require("aptos");
const aptos = require("@aptos-labs/ts-sdk");
const { NetworkToNetworkName, Network } = require("@aptos-labs/ts-sdk");

const APTOS_COIN = "0x1::aptos_coin::AptosCoin";
const COIN_STORE = `0x1::coin::CoinStore<${APTOS_COIN}>`;
const ALICE_INITIAL_BALANCE = 100_000_000;
const BOB_INITIAL_BALANCE = 100;
const TRANSFER_AMOUNT = 100;
const APTOS_NETWORK = NetworkToNetworkName[process.env.APTOS_NETWORK] || Network.DEVNET;

/**
* Prints the balance of an account
Expand All @@ -32,7 +34,7 @@ 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 aptos.AptosConfig({ network: aptos.Network.DEVNET });
const config = new aptos.AptosConfig({ network: APTOS_NETWORK });
const sdk = new aptos.Aptos(config);

// Create two accounts
Expand Down
2 changes: 2 additions & 0 deletions examples/typescript/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
auto-install-peers=true
strict-peer-dependencies=false
15 changes: 11 additions & 4 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 @@ -8,9 +10,14 @@
* `<Req, Res>(requestOptions: ClientRequest<Req>): Promise<ClientResponse<Res>>;`
*
*/
import { Aptos, AptosConfig, ClientResponse, ClientRequest } from "aptos";
import "dotenv";
import { Aptos, AptosConfig, ClientResponse, ClientRequest, Network, NetworkToNetworkName } from "@aptos-labs/ts-sdk";
// eslint-disable-next-line import/no-commonjs
const superagent = require("superagent");

// Default to devnet, but allow for overriding
const APTOS_NETWORK: Network = NetworkToNetworkName[process.env.APTOS_NETWORK] || Network.DEVNET;

export async function fetchCustomClient<Req, Res>(requestOptions: ClientRequest<Req>): Promise<ClientResponse<Res>> {
const { params, method, url, headers, body } = requestOptions;

Expand Down Expand Up @@ -65,10 +72,10 @@ export async function superagentCustomClient<Req, Res>(
}

const example = async () => {
console.log("This example demonstrate how one can config for a custom client ot be used by the SDK");
console.log("This example demonstrate how one can config for a custom client to be used by the SDK");

async function withSuperagentClient() {
const config = new AptosConfig({ client: { provider: superagentCustomClient } });
const config = new AptosConfig({ network: APTOS_NETWORK, client: { provider: superagentCustomClient } });
const aptos = new Aptos(config);

console.log(`\nclient being used ${config.client.provider.name}`);
Expand All @@ -78,7 +85,7 @@ const example = async () => {
}

async function withFetchClient() {
const config = new AptosConfig({ client: { provider: fetchCustomClient } });
const config = new AptosConfig({ network: APTOS_NETWORK, client: { provider: fetchCustomClient } });
const aptos = new Aptos(config);

console.log(`\nclient being used ${config.client.provider.name}`);
Expand Down
21 changes: 14 additions & 7 deletions examples/typescript/mint_nft.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
/* 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 "dotenv";
import { Account, Aptos, AptosConfig, Network, NetworkToNetworkName } from "@aptos-labs/ts-sdk";

const ALICE_INITIAL_BALANCE = 100_000_000;

// Default to devnet, but allow for overriding
const APTOS_NETWORK: Network = NetworkToNetworkName[process.env.APTOS_NETWORK] || Network.DEVNET;

/**
* Prints the balance of an account
* @param aptos
Expand All @@ -15,15 +22,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 +44,11 @@ const example = async () => {
);

// Setup the client
const config = new AptosConfig({ network: Network.DEVNET });
const config = new AptosConfig({ network: APTOS_NETWORK });
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 +80,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
Loading

0 comments on commit 884122c

Please sign in to comment.