Skip to content

Commit

Permalink
Finish the token related API for alpha (#88)
Browse files Browse the repository at this point in the history
* Add getTokenCurrentOwnerData and getTokenActivities queries

* get ownedTokens fetch

* add mintToken

* update doc

* update

* add example

* update

* Update src/api/token.ts

Co-authored-by: Maayan <[email protected]>

---------

Co-authored-by: Maayan <[email protected]>
  • Loading branch information
heliuchuan and 0xmaayan authored Oct 18, 2023
1 parent a82e996 commit 102ef95
Show file tree
Hide file tree
Showing 11 changed files with 641 additions and 19 deletions.
106 changes: 106 additions & 0 deletions examples/typescript/mint_nft.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/**
* This example shows how to use the Aptos client to mint a NFT.
*/

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

const ALICE_INITIAL_BALANCE = 100_000_000;

/**
* Prints the balance of an account
* @param aptos
* @param name
* @param address
* @returns {Promise<*>}
*
*/
const accountTokens = async (aptos: Aptos, name: string, accountAddress: string) => {
let 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++) {
const token = tokens[index];
console.log(
`*${token.current_token_data.token_name}* in the *${token.current_token_data.current_collection.collection_name}* collection`,
);
}
};

const example = async () => {
console.log(
"This example will create and fund an account (Alice), then the account will create a collection and a token in that collection.",
);

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

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

console.log("=== Addresses ===\n");
console.log(`Alice's address is: ${alice.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 collectionName = "Example Collection";
const collectionDescription = "Example description.";
const collectionURI = "aptos.dev";

// Create the collection
let transaction = await aptos.createCollectionTransaction({
creator: alice,
description: collectionDescription,
name: collectionName,
uri: collectionURI,
});

console.log("\n=== Create the collection ===\n");
let committedTxn = await aptos.signAndSubmitTransaction({ signer: alice, transaction });

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

console.log(`Created collection:`);
let exampleCollection = await aptos.getCollectionData({
collectionName,
creatorAddress: alice.accountAddress.toString(),
});
console.log(exampleCollection);

await accountTokens(aptos, "Alice", alice.accountAddress.toString());

const tokenName = "Example Token";
const tokenDescription = "Example token description.";
const tokenURI = "aptos.dev/token";

// Mint the token
transaction = await aptos.mintTokenTransaction({
creator: alice,
collection: collectionName,
description: tokenDescription,
name: tokenName,
uri: tokenURI,
});

console.log("\n=== Mint the token ===\n");
committedTxn = await aptos.signAndSubmitTransaction({ signer: alice, transaction });
await aptos.waitForTransaction({ transactionHash: committedTxn.hash });
console.log(`Committed transaction: ${committedTxn.hash}`);

await accountTokens(aptos, "Alice", alice.accountAddress.toString());
};

example();
1 change: 1 addition & 0 deletions examples/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"scripts": {
"multi_agent_transfer": "ts-node multi_agent_transfer.ts",
"simple_transfer": "ts-node simple_transfer.ts",
"mint_nft": "ts-node mint_nft.ts",
"simple_sponsored_transaction": "ts-node simple_sponsored_transaction.ts",
"transfer_coin": "ts-node transfer_coin.ts"
},
Expand Down
86 changes: 83 additions & 3 deletions src/api/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,24 @@
// SPDX-License-Identifier: Apache-2.0

import { AptosConfig } from "./aptosConfig";
import { getTokenData } from "../internal/token";
import { GetTokenDataResponse, HexInput } from "../types";
import {
getCurrentTokenOwnership,
getOwnedTokens,
getTokenActivity,
getTokenData,
mintTokenTransaction,
} from "../internal/token";
import {
GetCurrentTokenOwnershipResponse,
GetOwnedTokensResponse,
GetTokenActivityResponse,
GetTokenDataResponse,
HexInput,
OrderBy,
PaginationArgs,
} from "../types";
import { Account } from "../core";
import { GenerateTransactionOptions, SingleSignerTransaction } from "../transactions/types";

/**
* A class to query all `Token` related queries on Aptos.
Expand All @@ -16,12 +32,76 @@ export class Token {
}

/**
* This gets token data given the address of a token.
* Create a transaction to mint a token into the creators account within an existing collection.
*
* @param args.creator the creator of the collection
* @param args.collection the name of the collection the token belongs to
* @param args.description the description of the token
* @param args.name the name of the token
* @param args.uri the URI to additional info about the token
*
* @returns A SingleSignerTransaction that can be simulated or submitted to chain
*/
async mintTokenTransaction(args: {
creator: Account;
collection: string;
description: string;
name: string;
uri: string;
options?: GenerateTransactionOptions;
}): Promise<SingleSignerTransaction> {
return mintTokenTransaction({ aptosConfig: this.config, ...args });
}

/**
* Gets token data given the address of a token.
*
* @param args.tokenAddress The address of the token
* @returns GetTokenDataResponse containing relevant data to the token.
*/
async getTokenData(args: { tokenAddress: HexInput }): Promise<GetTokenDataResponse> {
return getTokenData({ aptosConfig: this.config, ...args });
}

/**
* Gets token ownership data given the address of a token.
*
* @param args.tokenAddress The address of the token
* @returns GetCurrentTokenOwnershipResponse containing relevant ownership data of the token.
*/
async getCurrentTokenOwnership(args: { tokenAddress: HexInput }): Promise<GetCurrentTokenOwnershipResponse> {
return getCurrentTokenOwnership({ aptosConfig: this.config, ...args });
}

/**
* Gets the tokens that the given address owns.
*
* @param args.ownerAddress The address of the owner
* @returns GetOwnedTokensResponse containing ownership data of the tokens belonging to the ownerAddresss.
*/
async getOwnedTokens(args: {
ownerAddress: HexInput;
options?: {
pagination?: PaginationArgs;
orderBy?: OrderBy<GetOwnedTokensResponse[0]>;
};
}): Promise<GetOwnedTokensResponse> {
return getOwnedTokens({ aptosConfig: this.config, ...args });
}

/**
* Gets the activity data given the address of a token.
*
* @param args.tokenAddress The address of the token
* @returns GetTokenActivityResponse containing relevant activity data to the token.
*/
async getTokenActivity(args: {
tokenAddress: HexInput;
options?: {
pagination?: PaginationArgs;
orderBy?: OrderBy<GetTokenActivityResponse[0]>;
};
}): Promise<GetTokenActivityResponse> {
return getTokenActivity({ aptosConfig: this.config, ...args });
}
}
17 changes: 17 additions & 0 deletions src/internal/queries/TokenActivitiesFieldsFragment.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
fragment TokenActivitiesFields on token_activities_v2 {
after_value
before_value
entry_function_id_str
event_account_address
event_index
from_address
is_fungible_v2
property_version_v1
to_address
token_amount
token_data_id
token_standard
transaction_timestamp
transaction_version
type
}
11 changes: 11 additions & 0 deletions src/internal/queries/getTokenActivity.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#import "./TokenActivitiesFieldsFragment";
query getTokenActivity(
$where_condition: token_activities_v2_bool_exp!
$offset: Int
$limit: Int
$order_by: [token_activities_v2_order_by!]
) {
token_activities_v2(where: $where_condition, order_by: $order_by, offset: $offset, limit: $limit) {
...TokenActivitiesFields
}
}
11 changes: 11 additions & 0 deletions src/internal/queries/getTokenCurrentOwner.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#import "./CurrentTokenOwnershipFieldsFragment";
query getCurrentTokenOwnership(
$where_condition: current_token_ownerships_v2_bool_exp!
$offset: Int
$limit: Int
$order_by: [current_token_ownerships_v2_order_by!]
) {
current_token_ownerships_v2(where: $where_condition, offset: $offset, limit: $limit, order_by: $order_by) {
...CurrentTokenOwnershipFields
}
}
Loading

0 comments on commit 102ef95

Please sign in to comment.