Skip to content

Commit

Permalink
add your_coin example
Browse files Browse the repository at this point in the history
  • Loading branch information
0xmaayan committed Nov 27, 2023
1 parent 7b85dc0 commit d30210d
Show file tree
Hide file tree
Showing 12 changed files with 311 additions and 85 deletions.
1 change: 1 addition & 0 deletions examples/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"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 yourCoin/index.ts",
"test": "run-s simple_transfer mint_nft multi_agent_transfer simple_sponsored_transaction transfer_coin custom_client publish_package_from_filepath external_signing"
},
"keywords": [],
Expand Down
14 changes: 2 additions & 12 deletions examples/typescript/publish_package_from_filepath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@
/* eslint-disable max-len */

import assert from "assert";
import fs from "fs";
import path from "path";
import { Account, Aptos, AptosConfig, Hex, Network, NetworkToNetworkName } from "@aptos-labs/ts-sdk";
import { compilePackage } from "./utils";
import { compilePackage, getPackageBytesToPublish } from "./utils";

const APTOS_NETWORK: Network = NetworkToNetworkName[process.env.APTOS_NETWORK] || Network.DEVNET;

Expand All @@ -34,15 +32,7 @@ async function main() {
console.log("\n=== Compiling the package locally ===");
compilePackage("facoin", "facoin/facoin.json", [{ name: "FACoin", address: alice.accountAddress }]);

// current working directory - the root folder of this repo
const cwd = process.cwd();
// target directory - current working directory + facoin/facoin.json (facoin.json is generated with the prevoius cli command)
const modulePath = path.join(cwd, "facoin/facoin.json");

const jsonData = JSON.parse(fs.readFileSync(modulePath, "utf8"));

const metadataBytes = jsonData.args[0].value;
const byteCode = jsonData.args[1].value;
const { metadataBytes, byteCode } = getPackageBytesToPublish("facoin/facoin.json");

console.log("\n===Publishing FAcoin package===");
const transaction = await aptos.publishPackageTransaction({
Expand Down
6 changes: 1 addition & 5 deletions examples/typescript/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,7 @@
"target": "es2020",
"pretty": true
},
"include": [
"src",
"*.ts"
],
"paths": {
"@aptos/*": "../..",
"@aptos/*": "../.."
}
}
25 changes: 24 additions & 1 deletion examples/typescript/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { execSync } from "child_process";
import path from "path";
import fs from "fs";
import { AccountAddress } from "@aptos-labs/ts-sdk";

/* eslint-disable no-console */
/* eslint-disable max-len */

/**
* A convenience function to compile a package locally with the CLI
* @param packageDir
Expand All @@ -21,11 +24,31 @@ export function compilePackage(
console.log("aptos is not installed. Please install it from the instructions on aptos.dev");
}

const addressArg = namedAddresses.map(({ name, address }) => `${name}=${address}`).join(" ");
const addressArg = namedAddresses.map(({ name, address }) => `${name}=${address.toString()}`).join(" ");

// Assume-yes automatically overwrites the previous compiled version, only do this if you are sure you want to overwrite the previous version.
const compileCommand = `aptos move build-publish-payload --json-output-file ${outputFile} --package-dir ${packageDir} --named-addresses ${addressArg} --assume-yes`;
console.log("Running the compilation locally, in a real situation you may want to compile this ahead of time.");
console.log(compileCommand);
execSync(compileCommand);
}

/**
* A convenience function to get the compiled package metadataBytes and byteCode
* @param packageDir
* @param outputFile
* @param namedAddresses
*/
export function getPackageBytesToPublish(filePath: string) {
// current working directory - the root folder of this repo
const cwd = process.cwd();
// target directory - current working directory + facoin/facoin.json (facoin.json is generated with the prevoius cli command)
const modulePath = path.join(cwd, filePath);

const jsonData = JSON.parse(fs.readFileSync(modulePath, "utf8"));

const metadataBytes = jsonData.args[0].value;
const byteCode = jsonData.args[1].value;

return { metadataBytes, byteCode };
}
142 changes: 142 additions & 0 deletions examples/typescript/yourCoin/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/* eslint-disable no-console */
/* eslint-disable max-len */

import { Account, AccountAddress, Aptos, AptosConfig, Network, NetworkToNetworkName } from "@aptos-labs/ts-sdk";
import { compilePackage, getPackageBytesToPublish } from "../utils";

/**
* This example demonstrate how one can publish a new custom coin to chain.
* It uses the MoonCoin.move module that can be found in this folder
*
* Before running this example, we should compile the package locally:
* 1. Acquire the Aptos CLI, see https://aptos.dev/cli-tools/aptos-cli/use-cli/install-aptos-cli
* 2. cd `~/aptos-ts-sdk/examples/typescript`
* 3. Run `pnpm run your_coin`
*/

const MOON_COINS_TO_MINT = 100;
const MOON_COINS_TO_TRANSFER = 100;

// 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);

/** Register the receiver account to receive transfers for the new coin. */
async function registerCoin(receiver: Account, coinTypeAddress: AccountAddress): Promise<string> {
const transaction = await aptos.build.transaction({
sender: receiver.accountAddress,
data: {
function: "0x1::managed_coin::register",
typeArguments: [`${coinTypeAddress.toString()}::moon_coin::MoonCoin`],
functionArguments: [],
},
});

const senderAuthenticator = aptos.sign.transaction({ signer: receiver, transaction });
const pendingTxn = await aptos.submit.transaction({ transaction, senderAuthenticator });

return pendingTxn.hash;
}

/** Transfer the newly created coin to a specified receiver address */
async function transferCoin(
sender: Account,
receiverAddress: AccountAddress,
amount: number | bigint,
): Promise<string> {
const transaction = await aptos.build.transaction({
sender: sender.accountAddress,
data: {
function: "0x1::aptos_account::transfer_coins",
typeArguments: [`${sender.accountAddress.toString()}::moon_coin::MoonCoin`],
functionArguments: [receiverAddress, amount],
},
});

const senderAuthenticator = aptos.sign.transaction({ signer: sender, transaction });
const pendingTxn = await aptos.submit.transaction({ transaction, senderAuthenticator });

return pendingTxn.hash;
}

/** Mints amount of the newly created coin to a specified receiver address */
async function mintCoin(minter: Account, receiverAddress: AccountAddress, amount: number): Promise<string> {
const transaction = await aptos.build.transaction({
sender: minter.accountAddress,
data: {
function: "0x1::managed_coin::mint",
typeArguments: [`${minter.accountAddress.toString()}::moon_coin::MoonCoin`],
functionArguments: [receiverAddress, amount],
},
});

const senderAuthenticator = aptos.sign.transaction({ signer: minter, transaction });
const pendingTxn = await aptos.submit.transaction({ transaction, senderAuthenticator });

return pendingTxn.hash;
}

/** Returns the balance of the newly created coin for an account */
const getBalance = async (accountAddress: AccountAddress, coinTypeAddress: AccountAddress) => {
const amount = await aptos.getAccountCoinAmount({
accountAddress,
coinType: `${coinTypeAddress.toString()}::moon_coin::MoonCoin`,
});

return amount;
};

async function main() {
// Create two accounts, Alice and Bob
const alice = Account.generate();
const bob = Account.generate();

console.log("\n=== Addresses ===");
console.log(`Alice: ${alice.accountAddress.toString()}`);
console.log(`Bob: ${bob.accountAddress.toString()}`);

// Fund alice account
await aptos.fundAccount({ accountAddress: alice.accountAddress, amount: 100_000_000 });

// Please ensure you have the aptos CLI installed
console.log("\n=== Compiling MoonCoin package locally ===");
compilePackage("yourCoin/moonCoin", "yourCoin/moonCoin/moonCoin.json", [
{ name: "MoonCoin", address: alice.accountAddress },
]);

const { metadataBytes, byteCode } = getPackageBytesToPublish("yourCoin/moonCoin/moonCoin.json");

console.log(`\n=== Publishing MoonCoin package to ${aptos.config.network} network ===`);

// Publish MoonCoin package to chain
const transaction = await aptos.publishPackageTransaction({
account: alice.accountAddress,
metadataBytes,
moduleBytecode: byteCode,
});

const pendingTransaction = await aptos.signAndSubmitTransaction({
signer: alice,
transaction,
});

console.log(`Publish package transaction hash: ${pendingTransaction.hash}`);
await aptos.waitForTransaction({ transactionHash: pendingTransaction.hash });

console.log(`Bob's initial MoonCoin balance: ${await getBalance(bob.accountAddress, alice.accountAddress)}.`);

console.log(`Alice mints herself ${MOON_COINS_TO_MINT} MoonCoin.`);
const registerCoinTransactionHash = await registerCoin(alice, alice.accountAddress);
await aptos.waitForTransaction({ transactionHash: registerCoinTransactionHash });

const mintCoinTransactionHash = await mintCoin(alice, alice.accountAddress, MOON_COINS_TO_MINT);
await aptos.waitForTransaction({ transactionHash: mintCoinTransactionHash });

console.log(`Alice transfers ${MOON_COINS_TO_TRANSFER} MoonCoin to Bob.`);
const transferCoinTransactionHash = await transferCoin(alice, bob.accountAddress, MOON_COINS_TO_TRANSFER);
await aptos.waitForTransaction({ transactionHash: transferCoinTransactionHash });
console.log(`Bob's updated MoonCoin balance: ${await getBalance(bob.accountAddress, alice.accountAddress)}.`);
}

main();
11 changes: 11 additions & 0 deletions examples/typescript/yourCoin/moonCoin/Move.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "MoonCoin"
version = "0.0.0"

[addresses]
MoonCoin = "_"

[dependencies.AptosFramework]
git = "https://github.com/aptos-labs/aptos-core.git"
rev = "mainnet"
subdir = "aptos-move/framework/aptos-framework"
16 changes: 16 additions & 0 deletions examples/typescript/yourCoin/moonCoin/moonCoin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"function_id": "0x1::code::publish_package_txn",
"type_args": [],
"args": [
{
"type": "hex",
"value": "0x084d6f6f6e436f696e0100000000000000004032344143313145423932453634313844304231433438373434313939313043444631453544454532383836333335383231353241353435444145423932454533aa011f8b08000000000002ff3d8db10ec2300c44777f05ca4ec28cc48090d8f882aa426962daa8c48ee2b4fc3e89689117dfdd3bbb4bd6cd76c41ec8463c5c0eeac14c370ea460c52c81a999275d470174d6fb8c22283dec60cb9f2df398903c920b28fa9a0acb3dd7a31fce730f63280d9c4a497236a6ca6919b4e3686c238f6f3bc8b63acea82ba020e3da4ad10622ac5a96c187dcac1f197945f3da9f6cf5bf56f005ed2121f8de00000001096d6f6f6e5f636f696eac011f8b08000000000002ff654e4b0ac23010dde7144317d2826b1751dcb8d61ea1c4765a82c944f241b0e4ee26412bd559bd79f33ea3cd1014c2d9183a19499ceb84ba3e419819a471de86de2f0298232bfc18082449dfe992503ba4012d878d9313a16ddef63ce2ee8deb462b343e8cbda50e4162c2a1d4709e53a450f289874fcbb15ecce58792bd5d71d72a8b21ababbf4bdb5e7ec8dd7a1d8572f8a59a7d819145f602f36168b21101000000000300000000000000000000000000000000000000000000000000000000000000010e4170746f734672616d65776f726b00000000000000000000000000000000000000000000000000000000000000010b4170746f735374646c696200000000000000000000000000000000000000000000000000000000000000010a4d6f76655374646c696200"
},
{
"type": "hex",
"value": [
"0xa11ceb0b060000000a01000402040403080b04130205151007254308684006a801150abd01050cc2011200000101000200000003000100010503010100010201060c0001080005060c0a020a020201096d6f6f6e5f636f696e0c6d616e616765645f636f696e084d6f6f6e436f696e0b696e69745f6d6f64756c650b64756d6d795f6669656c640a696e697469616c697a659c8916ead086418de2a9a041f507c0636c67107a196378cdbfe371f1724c452100000000000000000000000000000000000000000000000000000000000000010a020a094d6f6f6e20436f696e0a0205044d4f4f4e00020104010000000001070b000700070131060938000200"
]
}
]
}
5 changes: 5 additions & 0 deletions examples/typescript/yourCoin/moonCoin/scripts/register.move
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
script {
fun register(account: &signer) {
aptos_framework::managed_coin::register<MoonCoin::moon_coin::MoonCoin>(account)
}
}
13 changes: 13 additions & 0 deletions examples/typescript/yourCoin/moonCoin/sources/MoonCoin.move
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module MoonCoin::moon_coin {
struct MoonCoin {}

fun init_module(sender: &signer) {
aptos_framework::managed_coin::initialize<MoonCoin>(
sender,
b"Moon Coin",
b"MOON",
6,
false,
);
}
}
54 changes: 49 additions & 5 deletions src/api/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
} from "../types";
import {
deriveAccountFromPrivateKey,
getAccountCoinAmount,
getAccountCoinsCount,
getAccountCoinsData,
getAccountCollectionsWithOwnedTokens,
Expand All @@ -40,6 +41,7 @@ import {
import { ProcessorType } from "../utils/const";
import { AptosConfig } from "./aptosConfig";
import { waitForIndexerOnVersion } from "./utils";
import { CurrentFungibleAssetBalancesBoolExp } from "../types/generated/types";

/**
* A class to query all `Account` related queries on Aptos.
Expand Down Expand Up @@ -356,9 +358,10 @@ export class Account {
*
* @param args.accountAddress The account address we want to get the coins data for
* @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying
* @param args.options.pagination.offset The number coin to start returning results from
* @param args.options.pagination.limit The number of results to return
* @param args.options.orderBy The order to sort the coins by
* @param args.options.pagination.offset optional. The number coin to start returning results from
* @param args.options.pagination.limit optional. The number of results to return
* @param args.options.orderBy optional. The order to sort the coins by
* @param args.options.where optional. Filter the results by
* @returns Array with the coins data
*/
async getAccountCoinsData(args: {
Expand All @@ -367,6 +370,7 @@ export class Account {
options?: {
pagination?: PaginationArgs;
orderBy?: OrderBy<GetAccountCoinsDataResponse[0]>;
where?: CurrentFungibleAssetBalancesBoolExp;
};
}): Promise<GetAccountCoinsDataResponse> {
await waitForIndexerOnVersion({
Expand Down Expand Up @@ -399,14 +403,54 @@ export class Account {
return getAccountCoinsCount({ aptosConfig: this.config, ...args });
}

/**
* Queries the acount's APT amount
*
* @param args.accountAddress The account address we want to get the total count for
* @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying
* @returns Current amount of account's APT
*/
async getAccountAPTAmount(args: {
accountAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
}): Promise<number> {
await waitForIndexerOnVersion({
config: this.config,
minimumLedgerVersion: args.minimumLedgerVersion,
processorTypes: [ProcessorType.ACCOUNT_TRANSACTION_PROCESSOR],
});
return getAccountCoinAmount({ aptosConfig: this.config, coinType: "0x1::aptos_coin::AptosCoin", ...args });
}

/**
* Queries the acount's coin amount by the coin type
*
* @param args.accountAddress The account address we want to get the total count for
* @param args.coinType The coin type to query
* @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying
* @returns Current amount of account's coin
*/
async getAccountCoinAmount(args: {
accountAddress: AccountAddressInput;
coinType: MoveStructId;
minimumLedgerVersion?: AnyNumber;
}): Promise<number> {
await waitForIndexerOnVersion({
config: this.config,
minimumLedgerVersion: args.minimumLedgerVersion,
processorTypes: [ProcessorType.ACCOUNT_TRANSACTION_PROCESSOR],
});
return getAccountCoinAmount({ aptosConfig: this.config, ...args });
}

/**
* Queries an account's owned objects
*
* @param args.accountAddress The account address we want to get the objects for
* @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying
* @param args.options.pagination.offset The number coin to start returning results from
* @param args.options.pagination.offset The starting position to start returning results from
* @param args.options.pagination.limit The number of results to return
* @param args.options.orderBy The order to sort the coins by
* @param args.options.orderBy The order to sort the objects by
* @returns Objects array with the object data
*/
async getAccountOwnedObjects(args: {
Expand Down
Loading

0 comments on commit d30210d

Please sign in to comment.