Skip to content

Commit

Permalink
[examples] Add examples running in CI
Browse files Browse the repository at this point in the history
This runs all of the tests against local testnet, while defaulting
examples for users to devnet
  • Loading branch information
gregnazario committed Nov 1, 2023
1 parent 6a3cb58 commit 0929599
Show file tree
Hide file tree
Showing 12 changed files with 162 additions and 21 deletions.
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
17 changes: 11 additions & 6 deletions examples/typescript/custom_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,13 @@
* `<Req, Res>(requestOptions: ClientRequest<Req>): Promise<ClientResponse<Res>>;`
*
*/
import { Aptos, AptosConfig, ClientResponse, ClientRequest } from "aptos";
import { get as superAgentGet } from "superagent";
import "dotenv";
import { Aptos, AptosConfig, ClientResponse, ClientRequest, Network, toNetwork } from "aptos";
// eslint-disable-next-line import/no-commonjs
const superagent = require("superagent");

// Default to devnet, but allow for overriding
const APTOS_NETWORK: Network = toNetwork(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 @@ -55,7 +60,7 @@ export async function superagentCustomClient<Req, Res>(
method,
};

const response = await superAgentGet(`${url}?${params}`, request);
const response = await superagent.get(`${url}?${params}`, request);
return {
status: response.status,
statusText: response.statusText,
Expand All @@ -67,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 @@ -80,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
8 changes: 6 additions & 2 deletions examples/typescript/mint_nft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@
* This example shows how to use the Aptos client to mint a NFT.
*/

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

const ALICE_INITIAL_BALANCE = 100_000_000;

// Default to devnet, but allow for overriding
const APTOS_NETWORK: Network = toNetwork(process.env.APTOS_NETWORK) || Network.DEVNET;

/**
* Prints the balance of an account
* @param aptos
Expand Down Expand Up @@ -40,7 +44,7 @@ const example = async () => {
);

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

// Create the account
Expand Down
8 changes: 5 additions & 3 deletions examples/typescript/multi_agent_transfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@
/**
* This example shows how to use the Aptos client to create accounts, fund them, and transfer between them.
*/

import { Account, AccountAddress, Aptos, AptosConfig, U64, parseTypeTag } from "aptos";
import "dotenv";
import { Account, AccountAddress, Aptos, AptosConfig, U64, parseTypeTag, Network, toNetwork } 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 ALICE_INITIAL_BALANCE = 100_000_000;
const BOB_INITIAL_BALANCE = 100_000_000;
const TRANSFER_AMOUNT = 10;
// Default to devnet, but allow for overriding
const APTOS_NETWORK: Network = toNetwork(process.env.APTOS_NETWORK) || Network.DEVNET;

/**
* Prints the balance of an account
Expand Down Expand Up @@ -40,7 +42,7 @@ const example = async () => {
);

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

// Create two accounts
Expand Down
1 change: 1 addition & 0 deletions examples/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.3.1",
"npm-run-all": "latest",
"superagent": "^8.1.2"
},
Expand Down
8 changes: 8 additions & 0 deletions examples/typescript/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/typescript/publish_package_from_filepath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@
* 2. cd `~/aptos-ts-sdk/examples/typescript`
* 3. Run `pnpm run publish_package_from_filepath` and follow the prompt
*/
/* eslint-disable no-console */
/* eslint-disable max-len */

import assert from "assert";
import fs from "fs";
import path from "path";
import { Account, Aptos, Hex } from "aptos";
import { createInterface } from "readline";

const readline = require("readline").createInterface({
const readline = createInterface({
input: process.stdin,
output: process.stdout,
});
Expand Down Expand Up @@ -69,7 +72,7 @@ async function main() {
accountAddress: alice.accountAddress.toString(),
});
// published 2 modules
assert(accountModules.length == 2);
assert(accountModules.length === 2);
// first account's module bytecode equals the published bytecode
assert(accountModules[0].bytecode === `${Hex.fromHexInput(byteCode[0]).toString()}`);
// second account's module bytecode equals the published bytecode
Expand Down
8 changes: 6 additions & 2 deletions examples/typescript/simple_sponsored_transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,24 @@
* 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 } from "aptos";
import "dotenv";
import { Account, Aptos, AptosConfig, Network, toNetwork, U64 } from "aptos";

const ALICE_INITIAL_BALANCE = 100_000_000;
const SPONSOR_INITIAL_BALANCE = 100_000_000;
const BOB_INITIAL_BALANCE = 0;
const TRANSFER_AMOUNT = 10;
// Default to devnet, but allow for overriding
const APTOS_NETWORK: Network = toNetwork(process.env.APTOS_NETWORK) || Network.DEVNET;

const example = async () => {
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.",
);

// Setup the client
const aptos = new Aptos();
const aptosConfig = new AptosConfig({ network: APTOS_NETWORK });
const aptos = new Aptos(aptosConfig);

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

import { Account, AccountAddress, Aptos, AptosConfig, U64, parseTypeTag } from "aptos";
import { Account, AccountAddress, Aptos, AptosConfig, Network, parseTypeTag, toNetwork, U64 } 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";
Expand All @@ -13,6 +13,9 @@ const ALICE_INITIAL_BALANCE = 100_000_000;
const BOB_INITIAL_BALANCE = 100;
const TRANSFER_AMOUNT = 100;

// Default to devnet, but allow for overriding
const APTOS_NETWORK: Network = toNetwork(process.env.APTOS_NETWORK) || Network.DEVNET;

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

// Create two accounts
Expand Down
25 changes: 21 additions & 4 deletions examples/typescript/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,22 @@
* 5. Create a liquidity pool with Alice's FA and Bob's FA
* 6. Swap between Alice's FA and Bob's FA
*/

import { Account, AccountAddress, Aptos, Bool, Ed25519PrivateKey, U64, ViewRequestData } from "aptos";
import "dotenv";
import {
Account,
AccountAddress,
Aptos,
AptosConfig,
Bool,
Ed25519PrivateKey,
Network,
toNetwork,
U64,
ViewRequestData,
} from "aptos";
import { createInterface } from "readline";
// Default to devnet, but allow for overriding
const APTOS_NETWORK: Network = toNetwork(process.env.APTOS_NETWORK) || Network.DEVNET;

const readline = createInterface({
input: process.stdin,
Expand Down Expand Up @@ -199,10 +212,14 @@ const example = async () => {
process.exit(1);
}

const aptos = new Aptos();
const aptosConfig = new AptosConfig({ network: APTOS_NETWORK });
const aptos = new Aptos(aptosConfig);
// Create three accounts
const admin = Account.fromPrivateKeyAndAddress(new Ed25519PrivateKey(process.argv[3]));
const swapAddress = AccountAddress.fromHexInput(process.argv[2]);
const admin = Account.fromPrivateKeyAndAddress({
privateKey: new Ed25519PrivateKey(process.argv[3]),
address: swapAddress,
});

console.log("====== Account info ======\n");
console.log(`Admin's address is: ${admin.accountAddress.toString()}`);
Expand Down
17 changes: 17 additions & 0 deletions src/utils/apiEndpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,20 @@ export const NetworkToChainId: Record<string, number> = {
mainnet: 1,
testnet: 2,
};

export function toNetwork(network: string): Network | undefined {
switch (network) {
case "mainnet":
return Network.MAINNET;
case "testnet":
return Network.TESTNET;
case "devnet":
return Network.DEVNET;
case "local":
return Network.LOCAL;
case "custom":
return Network.CUSTOM;
default:
return undefined;
}
}

0 comments on commit 0929599

Please sign in to comment.