Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"keyless": "ts-node keyless.ts",
"keyless_mainnet": "ts-node keyless_mainnet.ts",
"local_node": "ts-node local_node.ts",
"rotate_key": "ts-node rotate_key.ts",
"swap": "ts-node swap.ts",
"test": "run-s simple_transfer simple_orderless_transfer multi_agent_transfer simple_sponsored_transaction transfer_coin custom_client publish_package_from_filepath external_signing sign_struct your_coin your_fungible_asset public_key_authenticator_account_abstraction hello_world_authenticator_account_abstraction"
},
Expand Down
26 changes: 18 additions & 8 deletions examples/typescript/rotate_key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,19 @@ import {
Aptos,
AptosConfig,
Ed25519Account,
MultiKey,
Network,
NetworkToNetworkName,
TransactionManager,
} from "@aptos-labs/ts-sdk";

const WIDTH = 16;

// Set up the client
const APTOS_NETWORK: Network = NetworkToNetworkName[process.env.APTOS_NETWORK ?? Network.DEVNET];
const APTOS_NETWORK: Network = NetworkToNetworkName[process.env.APTOS_NETWORK ?? Network.LOCAL];
const config = new AptosConfig({ network: APTOS_NETWORK });
const aptos = new Aptos(config);
const txnManager = TransactionManager.new(aptos);

function truncate(address: AccountAddress): string {
return `${address.toString().substring(0, 6)}...${address
Expand All @@ -32,8 +35,8 @@ function formatAccountInfo(account: Ed25519Account): string {
const alice = Account.generate();
const bob = Account.generate();

await aptos.fundAccount({ accountAddress: alice.accountAddress, amount: 1000000000 });
await aptos.fundAccount({ accountAddress: bob.accountAddress, amount: 1000000000 });
await txnManager.fundAccount(alice).submit();
await txnManager.fundAccount(bob).submit();

console.log(
`\n${"Account".padEnd(WIDTH)} ${"Address".padEnd(WIDTH)} ${"Auth Key".padEnd(WIDTH)} ${"Private Key".padEnd(
Expand All @@ -45,11 +48,18 @@ function formatAccountInfo(account: Ed25519Account): string {
console.log(`${"bob".padEnd(WIDTH)} ${formatAccountInfo(bob)}`);
console.log("\n...rotating...".padStart(WIDTH));

// Rotate the key!
await aptos.rotateAuthKey({ fromAccount: alice, toNewPrivateKey: bob.privateKey });
txnManager.defaultSender(alice);

const aliceNew = Account.fromPrivateKey({ privateKey: bob.privateKey, address: alice.accountAddress });
// Rotate the key!
await txnManager
.rotateAuthKeyUnverified({
toNewPublicKey: new MultiKey({
publicKeys: [bob.publicKey, alice.publicKey],
signaturesRequired: 1,
}),
})
.submit();

console.log(`\n${"alice".padEnd(WIDTH)} ${formatAccountInfo(aliceNew)}`);
console.log(`${"bob".padEnd(WIDTH)} ${formatAccountInfo(bob)}\n`);
// Transaction manager will derive the correct public key.
await txnManager.transferCoinTransaction({ recipient: bob.accountAddress, amount: 10 }).submit();
})();
28 changes: 14 additions & 14 deletions examples/typescript/simple_orderless_transfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
InputViewFunctionJsonData,
Network,
NetworkToNetworkName,
TransactionManager,
} from "@aptos-labs/ts-sdk";
import dotenv from "dotenv";
dotenv.config();
Expand Down Expand Up @@ -50,6 +51,7 @@ const example = async () => {
// Set up the client
const config = new AptosConfig({ network: APTOS_NETWORK });
const aptos = new Aptos(config);
const sender = TransactionManager.new(aptos);

// Create two accounts
const alice = Account.generate();
Expand Down Expand Up @@ -85,23 +87,21 @@ const example = async () => {
if (bobBalance !== BOB_INITIAL_BALANCE) throw new Error("Bob's balance is incorrect");

// Transfer between users
const txn = await aptos.transaction.build.simple({
sender: alice.accountAddress,
data: {
function: "0x1::coin::transfer",
typeArguments: [APTOS_COIN],
functionArguments: [bob.accountAddress, TRANSFER_AMOUNT],
},
options: {
replayProtectionNonce: 12345,
},
});
const response = await sender
.build({
data: {
function: "0x1::coin::transfer",
typeArguments: [APTOS_COIN],
functionArguments: [bob.accountAddress, TRANSFER_AMOUNT],
},
})
.orderless(12345)
.sender(alice)
.submit();

console.log("\n=== Transfer transaction ===\n");
const committedTxn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: txn });

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

console.log("\n=== Balances after transfer ===\n");
const newAliceBalance = await balance(aptos, "Alice", alice.accountAddress);
Expand Down
40 changes: 13 additions & 27 deletions examples/typescript/simple_sponsored_transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 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, AptosConfig, Network, NetworkToNetworkName } from "@aptos-labs/ts-sdk";
import { Account, Aptos, AptosConfig, Network, NetworkToNetworkName, TransactionManager } from "@aptos-labs/ts-sdk";
import dotenv from "dotenv";
dotenv.config();

Expand All @@ -22,7 +22,7 @@ const example = async () => {
);

// Set up the client
const aptosConfig = new AptosConfig({ network: APTOS_NETWORK });
const aptosConfig = new AptosConfig({ network: Network.LOCAL });
const aptos = new Aptos(aptosConfig);

// Create three accounts
Expand Down Expand Up @@ -59,31 +59,17 @@ const example = async () => {
if (aliceBalanceBefore[0].amount !== ALICE_INITIAL_BALANCE) throw new Error("Alice's balance is incorrect");
if (sponsorBalanceBefore[0].amount !== SPONSOR_INITIAL_BALANCE) throw new Error("Sponsor's balance is incorrect");

// Generate a fee payer (aka sponsor) transaction
// with Alice as the sender and sponsor as the fee payer
console.log("\n=== Submitting Transaction ===\n");
const transaction = await aptos.transaction.build.simple({
sender: aliceAddress,
withFeePayer: true,
data: {
function: "0x1::aptos_account::transfer",
functionArguments: [bob.accountAddress, TRANSFER_AMOUNT],
},
});

// Sponsor signs
const sponsorSignature = aptos.transaction.signAsFeePayer({ signer: sponsor, transaction });

// Submit the transaction to chain
const committedTxn = await aptos.signAndSubmitTransaction({
signer: alice,
// TODO: This doesn't actually work here?
feePayerAuthenticator: sponsorSignature,
transaction,
});

console.log(`Submitted transaction: ${committedTxn.hash}`);
const response = await aptos.waitForTransaction({ transactionHash: committedTxn.hash });
const response = await TransactionManager.new(aptos)
.build({
data: {
function: "0x1::aptos_account::transfer",
functionArguments: [bob.accountAddress, TRANSFER_AMOUNT],
},
})
.sender(alice)
.feePayer(sponsor)
.network(Network.LOCAL)
.submit();

console.log("\n=== Balances after transfer ===\n");
const aliceBalanceAfter = await aptos.getAccountCoinsData({
Expand Down
136 changes: 61 additions & 75 deletions examples/typescript/transfer_between_fungible_stores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
InputViewFunctionData,
Network,
NetworkToNetworkName,
TransactionManager,
} from "@aptos-labs/ts-sdk";
import { compilePackage, getPackageBytesToPublish } from "./utils";

Expand All @@ -25,10 +26,11 @@ import { compilePackage, getPackageBytesToPublish } from "./utils";
*/

// Set up the client
const APTOS_NETWORK: Network = NetworkToNetworkName[process.env.APTOS_NETWORK ?? Network.DEVNET];
const APTOS_NETWORK: Network = NetworkToNetworkName[process.env.APTOS_NETWORK ?? Network.LOCAL];

const config = new AptosConfig({ network: APTOS_NETWORK });
const aptos = new Aptos(config);
const txnManager = TransactionManager.new(aptos);

/**
* Utility function to wait for a specified number of milliseconds
Expand All @@ -38,34 +40,32 @@ const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

/** Admin mint the newly created coin to the specified receiver address */
async function mintCoin(admin: Account, receiver: Account, amount: AnyNumber): Promise<string> {
const transaction = await aptos.transaction.build.simple({
sender: admin.accountAddress,
data: {
function: `${admin.accountAddress}::fa_coin::mint`,
functionArguments: [receiver.accountAddress, amount],
},
});

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

return pendingTxn.hash;
return (
await txnManager
.build({
data: {
function: `${admin.accountAddress}::fa_coin::mint`,
functionArguments: [receiver.accountAddress, amount],
},
})
.sender(admin)
.submit()
).hash;
}

/** Create a secondary store for a user */
async function createSecondaryStore(admin: Account, user: Account, metadata: AccountAddress): Promise<string> {
const transaction = await aptos.transaction.build.simple({
sender: user.accountAddress,
data: {
function: `${admin.accountAddress}::secondary_store::create_secondary_store`,
functionArguments: [metadata],
},
});

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

return pendingTxn.hash;
return (
await txnManager
.build({
data: {
function: `${admin.accountAddress}::secondary_store::create_secondary_store`,
functionArguments: [metadata],
},
})
.sender(user)
.submit()
).hash;
}

/** Get the primary store address for a user and metadata */
Expand Down Expand Up @@ -150,9 +150,9 @@ async function main() {

// Fund accounts
await Promise.all([
aptos.fundAccount({ accountAddress: alice.accountAddress, amount: 100_000_000 }),
aptos.fundAccount({ accountAddress: bob.accountAddress, amount: 100_000_000 }),
aptos.fundAccount({ accountAddress: charlie.accountAddress, amount: 100_000_000 }),
txnManager.defaultSender(alice).fundAccount().submit(),
txnManager.defaultSender(bob).fundAccount().submit(),
txnManager.defaultSender(charlie).fundAccount().submit(),
]);

// Compile and publish package
Expand All @@ -162,19 +162,15 @@ async function main() {
const { metadataBytes, byteCode } = getPackageBytesToPublish("move/facoin/facoin.json");

console.log("\n=== Publishing FACoin package ===");
const transaction = await aptos.publishPackageTransaction({
account: alice.accountAddress,
metadataBytes,
moduleBytecode: byteCode,
});
const response = await aptos.signAndSubmitTransaction({
signer: alice,
transaction,
});
const response = await txnManager
.publishPackageTransaction({
metadataBytes,
moduleBytecode: byteCode,
})
.sender(alice)
.submit();

console.log(`Transaction hash: ${response.hash}`);
await aptos.waitForTransaction({
transactionHash: response.hash,
});

const metadataAddress = await getMetadata(alice);
console.log("metadata address:", metadataAddress);
Expand All @@ -188,8 +184,7 @@ async function main() {

// Mint initial coins
console.log("Alice mints Bob 10 FA coin.");
const mintCoinTransactionHash = await mintCoin(alice, bob, 1_000_000_000);
await aptos.waitForTransaction({ transactionHash: mintCoinTransactionHash });
await mintCoin(alice, bob, 1_000_000_000);

// Get store addresses
const bobPrimaryStoreAddress = await getPrimaryStore(bob, AccountAddress.from(metadataAddress));
Expand All @@ -206,51 +201,42 @@ async function main() {

// Transfer from primary to secondary store
console.log("\n=== Transferring from primary to secondary store ===");
const transferToSecondaryTxn = await aptos.transferFungibleAssetBetweenStores({
sender: bob,
fromStore: bobPrimaryStoreAddress,
toStore: bobSecondaryStore,
amount: 800_000_000,
});
const transferToSecondaryResponse = await aptos.signAndSubmitTransaction({
signer: bob,
transaction: transferToSecondaryTxn,
});
await aptos.waitForTransaction({ transactionHash: transferToSecondaryResponse.hash });
await txnManager
.transferFungibleAssetBetweenStores({
fromStore: bobPrimaryStoreAddress,
toStore: bobSecondaryStore,
amount: 800_000_000,
})
.sender(bob)
.submit();

// Display updated balances
await printBalances("Updated Balances", metadataAddress, bob, charlie);

// Transfer between secondary stores
console.log("\n=== Transferring between secondary stores ===");
const transferBetweenSecondaryTxn = await aptos.transferFungibleAssetBetweenStores({
sender: bob,
fromStore: bobSecondaryStore,
toStore: charlieSecondaryStore,
amount: 600_000_000,
});
const transferBetweenSecondaryResponse = await aptos.signAndSubmitTransaction({
signer: bob,
transaction: transferBetweenSecondaryTxn,
});
await aptos.waitForTransaction({ transactionHash: transferBetweenSecondaryResponse.hash });
await txnManager
.transferFungibleAssetBetweenStores({
fromStore: bobSecondaryStore,
toStore: charlieSecondaryStore,
amount: 600_000_000,
})
.sender(bob)
.submit();

// Display updated balances
await printBalances("Updated Balances", metadataAddress, bob, charlie);

// Transfer from secondary store to primary store
console.log("\n=== Transferring from secondary to primary store ===");
const transferFromSecondaryTxn = await aptos.transferFungibleAssetBetweenStores({
sender: charlie,
fromStore: charlieSecondaryStore,
toStore: bobPrimaryStoreAddress,
amount: 350_000_000,
});
const transferFromSecondaryResponse = await aptos.signAndSubmitTransaction({
signer: charlie,
transaction: transferFromSecondaryTxn,
});
await aptos.waitForTransaction({ transactionHash: transferFromSecondaryResponse.hash });
await txnManager
.transferFungibleAssetBetweenStores({
fromStore: charlieSecondaryStore,
toStore: bobPrimaryStoreAddress,
amount: 350_000_000,
})
.sender(charlie)
.submit();

// Display final balances
await printBalances("Final Balances", metadataAddress, bob, charlie);
Expand Down
Loading
Loading