Skip to content

Commit

Permalink
simple digital asset example and bug fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
0xmaayan committed Nov 29, 2023
1 parent ef6ffee commit 536eca8
Show file tree
Hide file tree
Showing 8 changed files with 185 additions and 122 deletions.
3 changes: 2 additions & 1 deletion examples/typescript-esm/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
"type": "module",
"scripts": {
"build": "pnpm _build:esm",
"_build:esm": "tsup simple_transfer.ts simple_sponsored_transaction.ts --platform node --format esm --dts --out-dir dist",
"_build:esm": "tsup simple_transfer.ts simple_sponsored_transaction.ts simple_digital_asset.ts --platform node --format esm --dts --out-dir dist",
"simple_transfer": "ts-node --esm dist/simple_transfer.js",
"simple_sponsored_transaction": "ts-node --esm dist/simple_sponsored_transaction.js",
"simple_digital_asset": "pnpm run build && ts-node --esm dist/simple_digital_asset.js",
"test": "run-s build simple_transfer simple_sponsored_transaction"
},
"keywords": [],
Expand Down
112 changes: 112 additions & 0 deletions examples/typescript-esm/simple_digital_asset.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/* eslint-disable no-console */
/* eslint-disable max-len */

/**
* This example shows how to use the Aptos client to mint and transfer a Digital Asset.
*/

import "dotenv";
import { Account, Aptos, AptosConfig, Network, NetworkToNetworkName } from "@aptos-labs/ts-sdk";

const INITIAL_BALANCE = 100_000_000;

// Setup the client
const APTOS_NETWORK: Network = NetworkToNetworkName[process.env.APTOS_NETWORK] || Network.DEVNET;
const config = new AptosConfig({ network: APTOS_NETWORK });
const aptos = new Aptos(config);

const example = async () => {
console.log(
"This example will create and fund Alice and Bob, then Alice account will create a collection and a digital asset in that collection and tranfer it to Bob.",
);

// Create Alice and Bob accounts
const alice = Account.generate();
const bob = Account.generate();

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

// Fund and create the accounts
await aptos.faucet.fundAccount({
accountAddress: alice.accountAddress,
amount: INITIAL_BALANCE,
});
await aptos.faucet.fundAccount({
accountAddress: bob.accountAddress,
amount: INITIAL_BALANCE,
});

const collectionName = "Example Collection";
const collectionDescription = "Example description.";
const collectionURI = "aptos.dev";

// Create the collection
const createCollectionTransaction = 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: createCollectionTransaction });

let pendingTxn = await aptos.waitForTransaction({ transactionHash: committedTxn.hash });

const alicesCollection = await aptos.getCollectionData({
creatorAddress: alice.accountAddress,
collectionName,
minimumLedgerVersion: BigInt(pendingTxn.version),
});
console.log(`Alice's collection: ${JSON.stringify(alicesCollection, null, 4)}`);

const tokenName = "Example Asset";
const tokenDescription = "Example asset description.";
const tokenURI = "aptos.dev/asset";

console.log("\n=== Alice Mints the digital asset ===\n");

const mintTokenTransaction = await aptos.mintTokenTransaction({
creator: alice,
collection: collectionName,
description: tokenDescription,
name: tokenName,
uri: tokenURI,
});

committedTxn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: mintTokenTransaction });
pendingTxn = await aptos.waitForTransaction({ transactionHash: committedTxn.hash });

const alicesDigitalAsset = await aptos.getOwnedTokens({
ownerAddress: alice.accountAddress,
minimumLedgerVersion: BigInt(pendingTxn.version),
});
console.log(`Alice's digital assets balance: ${alicesDigitalAsset.length}`);

console.log(`Alice's digital asset: ${JSON.stringify(alicesDigitalAsset[0], null, 4)}`);

console.log("\n=== Transfer the digital asset to Bob ===\n");

const transferTransaction = await aptos.transferDigitalAsset({
sender: alice,
digitalAssetAddress: alicesDigitalAsset[0].token_data_id,
recipient: bob.accountAddress,
});
committedTxn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: transferTransaction });
pendingTxn = await aptos.waitForTransaction({ transactionHash: committedTxn.hash });

const alicesDigitalAssetsAfter = await aptos.getOwnedTokens({
ownerAddress: alice.accountAddress,
minimumLedgerVersion: BigInt(pendingTxn.version),
});
console.log(`Alices's digital assets balance: ${alicesDigitalAssetsAfter.length}`);

const bobDigitalAssetsAfter = await aptos.getOwnedTokens({
ownerAddress: bob.accountAddress,
minimumLedgerVersion: BigInt(pendingTxn.version),
});
console.log(`Bob's digital assets balance: ${bobDigitalAssetsAfter.length}`);
};

example();
113 changes: 0 additions & 113 deletions examples/typescript/mint_nft.ts

This file was deleted.

3 changes: 1 addition & 2 deletions examples/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@
"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",
"custom_client": "ts-node custom_client.ts",
"swap": "ts-node swap.ts",
"publish_package_from_filepath": "ts-node publish_package_from_filepath.ts",
"external_signing": "ts-node external_signing.ts",
"your_coin": "ts-node your_coin.ts",
"test": "run-s simple_transfer mint_nft multi_agent_transfer simple_sponsored_transaction transfer_coin custom_client publish_package_from_filepath external_signing"
"test": "run-s simple_transfer multi_agent_transfer simple_sponsored_transaction transfer_coin custom_client publish_package_from_filepath external_signing"
},
"keywords": [],
"author": "",
Expand Down
25 changes: 24 additions & 1 deletion src/api/digitalAsset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ import {
GetOwnedTokensResponse,
GetTokenActivityResponse,
GetTokenDataResponse,
MoveStructId,
OrderByArg,
PaginationArgs,
TokenStandard,
TokenStandardArg,
} from "../types";
import { Account, AccountAddressInput } from "../core";
import { Account, AccountAddress, AccountAddressInput } from "../core";
import { InputGenerateTransactionOptions, SingleSignerTransaction } from "../transactions/types";
import {
CreateCollectionOptions,
Expand All @@ -25,6 +26,7 @@ import {
getTokenActivity,
getTokenData,
mintTokenTransaction,
transferDigitalAsset,
} from "../internal/digitalAsset";
import { ProcessorType } from "../utils/const";
import { AptosConfig } from "./aptosConfig";
Expand Down Expand Up @@ -228,6 +230,27 @@ export class DigitalAsset {
});
return getTokenActivity({ aptosConfig: this.config, ...args });
}

/**
* Transfer a digital asset (non fungible token) ownership.
* We can transfer a digital asset only when the digital asset is not frozen (i.e. owner transfer is not disabled such as for soul bound tokens)

Check failure on line 236 in src/api/digitalAsset.ts

View workflow job for this annotation

GitHub Actions / run-tests

This line has a length of 146. Maximum allowed is 130
*
* @param args.sender The sender account of the current token owner
* @param args.digitalAssetAddress The digital asset address
* @param args.recipient The recipient account address
* @param args.digitalAssetType optional. The digital asset type, default to "0x4::token::Token"
*
* @returns A SingleSignerTransaction that can be simulated or submitted to chain
*/
async transferDigitalAsset(args: {
sender: Account;
digitalAssetAddress: AccountAddressInput;
recipient: AccountAddress;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SingleSignerTransaction> {
return transferDigitalAsset({ aptosConfig: this.config, ...args });
}
}

function getTokenProcessorTypes(tokenStandard?: TokenStandard) {
Expand Down
24 changes: 24 additions & 0 deletions src/internal/digitalAsset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
GetOwnedTokensResponse,
GetTokenActivityResponse,
GetTokenDataResponse,
MoveStructId,
OrderByArg,
PaginationArgs,
TokenStandardArg,
Expand Down Expand Up @@ -138,6 +139,7 @@ export async function getOwnedTokens(args: {

const whereCondition: CurrentTokenOwnershipsV2BoolExp = {
owner_address: { _eq: AccountAddress.from(ownerAddress).toStringLong() },
amount: { _gt: 0 },
};

const graphqlQuery = {
Expand Down Expand Up @@ -285,3 +287,25 @@ export async function getCollectionId(args: {
}): Promise<string> {
return (await getCollectionData(args)).collection_id;
}

export async function transferDigitalAsset(args: {
aptosConfig: AptosConfig;
sender: Account;
digitalAssetAddress: AccountAddressInput;
recipient: AccountAddress;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SingleSignerTransaction> {
const { aptosConfig, sender, digitalAssetAddress, recipient, digitalAssetType, options } = args;
const transaction = await generateTransaction({
aptosConfig,
sender: sender.accountAddress,
data: {
function: "0x1::object::transfer",
typeArguments: [digitalAssetType ?? "0x4::token::Token"],
functionArguments: [digitalAssetAddress, recipient],
},
options,
});
return transaction;
}
4 changes: 2 additions & 2 deletions src/internal/fungibleAsset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import {
FungibleAssetMetadataBoolExp,
} from "../types/generated/types";
import { Account, AccountAddress } from "../core";
import { InputGenerateTransactionOptions } from "../transactions";
import { InputGenerateTransactionOptions, SingleSignerTransaction } from "../transactions";
import { generateTransaction } from "./transactionSubmission";

export async function getFungibleAssetMetadata(args: {
Expand Down Expand Up @@ -116,7 +116,7 @@ export async function transferFungibleAsset(args: {
recipient: AccountAddress;
amount: AnyNumber;
options?: InputGenerateTransactionOptions;
}) {
}): Promise<SingleSignerTransaction> {
const { aptosConfig, sender, fungibleAssetMetadataAddress, recipient, amount, options } = args;
const transaction = await generateTransaction({
aptosConfig,
Expand Down
Loading

0 comments on commit 536eca8

Please sign in to comment.