Skip to content

Commit

Permalink
share aptos-nodejs-scripts module
Browse files Browse the repository at this point in the history
  • Loading branch information
lmaoevd committed Nov 4, 2022
1 parent 9d93862 commit 8eff22d
Show file tree
Hide file tree
Showing 11 changed files with 2,837 additions and 6 deletions.
Binary file modified .DS_Store
Binary file not shown.
Binary file added aptos-nodejs-script/.DS_Store
Binary file not shown.
2,100 changes: 2,100 additions & 0 deletions aptos-nodejs-script/package-lock.json

Large diffs are not rendered by default.

24 changes: 24 additions & 0 deletions aptos-nodejs-script/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "aptos-arbitrage",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@pontem/liquidswap-sdk": "^0.0.1",
"aptos": "^1.3.14",
"dotenv": "^16.0.2",
"ethers": "^5.7.2",
"mysql": "^2.18.1",
"tslib": "^2.4.0"
},
"devDependencies": {
"@types/node": "^18.7.23",
"ts-node": "^10.9.1",
"typescript": "^4.8.4"
}
}
22 changes: 16 additions & 6 deletions aptos-nodejs-script/readme.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
# Aptos上的Liquidswap和AnimeSwap之间的套利代码
# Aptos Nodejs的脚本代码分享

0. 替换Move.toml中的lmao地址成自己用来部署合约的钱包地址
## 安装
1. `cp ./.env.example ./.env`
2. `npm i`
3. 配置.env中需要用到的内容

1. 编译
`aptos move compile --save-metadata --package-dir ./`
2. 部署
`aptos move publish`

## scripts 脚本
### examples 示例脚本
1. bsc_transaction.js (官方示例)
2. simple_nft.js (官方示例)
3. transfer_coin.js (官方示例)
4. your_coin.js (官方示例)

### production 正式环境脚本
1. accounts.js (批量生成帐号并录入Mysql数据库)
2. liquidswap.js (Liquidswap官方Sdk的使用 - 一个生成交易信息并模拟提交,到签名提交的实用入门示例)
98 changes: 98 additions & 0 deletions aptos-nodejs-script/scripts/examples/bcs_transaction.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/* eslint-disable no-console */

const dotenv = require("dotenv") ;
dotenv.config();

const { AptosClient, AptosAccount, FaucetClient, BCS, TxnBuilderTypes, HexString } = require("aptos");
const aptosCoinStore = "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>";
const assert = require("assert");

const NODE_URL = process.env.APTOS_NODE_URL || "https://fullnode.devnet.aptoslabs.com";
const FAUCET_URL = process.env.APTOS_FAUCET_URL || "https://faucet.devnet.aptoslabs.com";

const {
AccountAddress,
TypeTagStruct,
EntryFunction,
StructTag,
TransactionPayloadEntryFunction,
RawTransaction,
ChainId,
} = TxnBuilderTypes;

/**
* This code example demonstrates the process of moving test coins from one account to another.
*/
(async () => {
const client = new AptosClient(NODE_URL);
const faucetClient = new FaucetClient(NODE_URL, FAUCET_URL);

// Generates key pair for a new account
const account1 = new AptosAccount(new HexString(process.env.MAIN_WALLET_PRIVATE_KEY).toUint8Array());
await faucetClient.fundAccount(account1.address(), 100_000_000);
let resources = await client.getAccountResources(account1.address());
let accountResource = resources.find((r) => r.type === aptosCoinStore);
let balance = parseInt((accountResource?.data).coin.value);
assert(balance >= 100_000_000);
console.log(`account2 coins: ${balance}. Should > 100000000!`);

const account2 = new AptosAccount(undefined, "0x2f0434fe778ae6f330e8ddef05ed391e7dad5683785b95c6903adf01f9c05f3a"); // <:!:section_2
// Creates the second account and fund the account with 0 AptosCoin
await faucetClient.fundAccount(account2.address(), 0);
resources = await client.getAccountResources(account2.address());
accountResource = resources.find((r) => r.type === aptosCoinStore);
balance = parseInt((accountResource?.data).coin.value);
assert(balance >= 0);
console.log(`account2 coins: ${balance}. Should > 0!`);

const token = new TypeTagStruct(StructTag.fromString("0x1::aptos_coin::AptosCoin"));

// TS SDK support 3 types of transaction payloads: `EntryFunction`, `Script` and `Module`.
// See https://aptos-labs.github.io/ts-sdk-doc/ for the details.
const entryFunctionPayload = new TransactionPayloadEntryFunction(
EntryFunction.natural(
// Fully qualified module name, `AccountAddress::ModuleName`
"0x1::coin",
// Module function
"transfer",
// The coin type to transfer
[token],
// Arguments for function `transfer`: receiver account address and amount to transfer
[BCS.bcsToBytes(AccountAddress.fromHex(account2.address())), BCS.bcsSerializeUint64(717)],
),
);

const [{ sequence_number: sequenceNumber }, chainId] = await Promise.all([
client.getAccount(account1.address()),
client.getChainId(),
]);

// See class definiton here
// https://aptos-labs.github.io/ts-sdk-doc/classes/TxnBuilderTypes.RawTransaction.html#constructor.
const rawTxn = new RawTransaction(
// Transaction sender account address
AccountAddress.fromHex(account1.address()),
BigInt(sequenceNumber),
entryFunctionPayload,
// Max gas unit to spend
BigInt(2000),
// Gas price per unit
BigInt(100),
// Expiration timestamp. Transaction is discarded if it is not executed within 10 seconds from now.
BigInt(Math.floor(Date.now() / 1000) + 10),
new ChainId(chainId),
);

// Sign the raw transaction with account1's private key
const bcsTxn = AptosClient.generateBCSTransaction(account1, rawTxn);

const transactionRes = await client.submitSignedBCSTransaction(bcsTxn);

await client.waitForTransaction(transactionRes.hash);

resources = await client.getAccountResources(account2.address());
accountResource = resources.find((r) => r.type === aptosCoinStore);
balance = parseInt((accountResource?.data).coin.value);
assert(balance >= 717);
console.log(`account2 coins: ${balance}. Should >= 717!`);
})();
164 changes: 164 additions & 0 deletions aptos-nodejs-script/scripts/examples/simple_nft.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

/* eslint-disable no-console */

const dotenv = require("dotenv");
dotenv.config();

const { AptosClient, AptosAccount, FaucetClient, TokenClient, CoinClient, HexString } = require("aptos");
const NODE_URL = process.env.APTOS_NODE_URL || "https://fullnode.devnet.aptoslabs.com";
const FAUCET_URL = process.env.APTOS_FAUCET_URL || "https://faucet.devnet.aptoslabs.com";

(async () => {
// Create API and faucet clients.
// :!:>section_1a
const client = new AptosClient(NODE_URL);
const faucetClient = new FaucetClient(NODE_URL, FAUCET_URL); // <:!:section_1a

// Create client for working with the token module.
// :!:>section_1b
const tokenClient = new TokenClient(client); // <:!:section_1b

// Create a coin client for checking account balances.
const coinClient = new CoinClient(client);

// Create accounts.
// :!:>section_2
const alice = new AptosAccount(new HexString(process.env.MAIN_WALLET_PRIVATE_KEY).toUint8Array());
const bob = new AptosAccount(new HexString(process.env.BOB_WALLET_PRIVATE_KEY).toUint8Array()); // <:!:section_2

// Print out account addresses.
console.log("=== Addresses ===");
console.log(`Alice: ${alice.address()}`);
console.log(`Bob: ${bob.address()}`);
console.log("");

// Fund accounts.
// :!:>section_3
await faucetClient.fundAccount(alice.address(), 100_000_000);
await faucetClient.fundAccount(bob.address(), 100_000_000); // <:!:section_3

console.log("=== Initial Coin Balances ===");
console.log(`Alice: ${await coinClient.checkBalance(alice)}`);
console.log(`Bob: ${await coinClient.checkBalance(bob)}`);
console.log("");

console.log("=== Creating Collection and Token ===");

const collectionName = "Alice's 2"; // 链上若已存在collectionName,不能再次重复创建,否则Evm会报错
const tokenName = "Alice's first token";
const tokenPropertyVersion = 0;

const tokenId = {
token_data_id: {
creator: alice.address().hex(),
collection: collectionName,
name: tokenName,
},
property_version: `${tokenPropertyVersion}`,
};

// Create the collection.
// :!:>section_4
const txnHash1 = await tokenClient.createCollection(
alice,
collectionName,
"Alice's simple collection",
"https://alice.com",
); // <:!:section_4
await client.waitForTransaction(txnHash1, { checkSuccess: true });

// Create a token in that collection.
// :!:>section_5
const txnHash2 = await tokenClient.createToken(
alice,
collectionName,
tokenName,
"Alice's simple token",
1,
"https://aptos.dev/img/nyan.jpeg",
); // <:!:section_5
await client.waitForTransaction(txnHash2, { checkSuccess: true });

// Print the collection data.
// :!:>section_6
const collectionData = await tokenClient.getCollectionData(alice.address(), collectionName);
console.log(`Alice's collection: ${JSON.stringify(collectionData, null, 4)}`); // <:!:section_6

// Get the token balance.
// :!:>section_7
const aliceBalance1 = await tokenClient.getToken(
alice.address(),
collectionName,
tokenName,
`${tokenPropertyVersion}`,
);
console.log(`Alice's token balance: ${aliceBalance1["amount"]}`); // <:!:section_7

// Get the token data.
// :!:>section_8
const tokenData = await tokenClient.getTokenData(alice.address(), collectionName, tokenName);
console.log(`Alice's token data: ${JSON.stringify(tokenData, null, 4)}`); // <:!:section_8

// Alice offers one token to Bob.
console.log("\n=== Transferring the token to Bob ===");
// :!:>section_9
const txnHash3 = await tokenClient.offerToken(
alice,
bob.address(),
alice.address(),
collectionName,
tokenName,
1,
tokenPropertyVersion,
); // <:!:section_9
await client.waitForTransaction(txnHash3, { checkSuccess: true });

// Bob claims the token Alice offered him.
// :!:>section_10
const txnHash4 = await tokenClient.claimToken(
bob,
alice.address(),
alice.address(),
collectionName,
tokenName,
tokenPropertyVersion,
); // <:!:section_10
await client.waitForTransaction(txnHash4, { checkSuccess: true });

// Print their balances.
const aliceBalance2 = await tokenClient.getToken(
alice.address(),
collectionName,
tokenName,
`${tokenPropertyVersion}`,
);
const bobBalance2 = await tokenClient.getTokenForAccount(bob.address(), tokenId);
console.log(`Alice's token balance: ${aliceBalance2["amount"]}`);
console.log(`Bob's token balance: ${bobBalance2["amount"]}`);

console.log("\n=== Transferring the token back to Alice using MultiAgent ===");
// :!:>section_11
let txnHash5 = await tokenClient.directTransferToken(
bob,
alice,
alice.address(),
collectionName,
tokenName,
1,
tokenPropertyVersion,
); // <:!:section_11
await client.waitForTransaction(txnHash5, { checkSuccess: true });

// Print out their balances one last time.
const aliceBalance3 = await tokenClient.getToken(
alice.address(),
collectionName,
tokenName,
`${tokenPropertyVersion}`,
);
const bobBalance3 = await tokenClient.getTokenForAccount(bob.address(), tokenId);
console.log(`Alice's token balance: ${aliceBalance3["amount"]}`);
console.log(`Bob's token balance: ${bobBalance3["amount"]}`);
})();
70 changes: 70 additions & 0 deletions aptos-nodejs-script/scripts/examples/transfer_coin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

/* eslint-disable no-console */

const dotenv = require("dotenv") ;
dotenv.config();

const { AptosClient, AptosAccount, CoinClient, FaucetClient, HexString, TxnBuilderTypes,
TransactionBuilder } = require("aptos");
const NODE_URL = process.env.NODE_URL || "";
const FAUCET_URL = process.env.FAUCET_URL || "";

(async () => {
console.log(NODE_URL)
// Create API and faucet clients.
// :!:>section_1
const client = new AptosClient(NODE_URL);
const faucetClient = new FaucetClient(NODE_URL, FAUCET_URL); // <:!:section_1

// Create client for working with the coin module.
// :!:>section_1a
const coinClient = new CoinClient(client); // <:!:section_1a

// Create accounts.
// :!:>section_2
const alice = new AptosAccount(new HexString(process.env.MAIN_WALLET_PRIVATE_KEY).toUint8Array());
const bob = new AptosAccount(undefined, "0x2f0434fe778ae6f330e8ddef05ed391e7dad5683785b95c6903adf01f9c05f3a"); // <:!:section_2

// Print out account addresses.
console.log("=== Addresses ===");
console.log(`Alice: ${alice.address()}`);
console.log(`Bob: ${bob.address()}`);
console.log("");

// // Fund accounts.
// // :!:>section_3
await faucetClient.fundAccount(alice.address(), 100_000_000);
await faucetClient.fundAccount(bob.address(), 0); // <:!:section_3

// Print out initial balances.
console.log("=== Initial Balances ===");
// :!:>section_4
console.log(`Alice: ${await coinClient.checkBalance(alice)}`);
console.log(`Bob: ${await coinClient.checkBalance(bob)}`); // <:!:section_4
console.log("");

// Have Alice send Bob some AptosCoins.
// :!:>section_5
let txnHash = await coinClient.transfer(alice, bob, 1_000, { gasUnitPrice: BigInt(100) }); // <:!:section_5
// :!:>section_6a
await client.waitForTransaction(txnHash); // <:!:section_6a

// Print out intermediate balances.
console.log("=== Intermediate Balances ===");
console.log(`Alice: ${await coinClient.checkBalance(alice)}`);
console.log(`Bob: ${await coinClient.checkBalance(bob)}`);
console.log("");

// Have Alice send Bob some more AptosCoins.
txnHash = await coinClient.transfer(alice, bob, 1_000, { gasUnitPrice: BigInt(100) });
// :!:>section_6b
await client.waitForTransaction(txnHash, { checkSuccess: true }); // <:!:section_6b

// Print out final balances.
console.log("=== Final Balances ===");
console.log(`Alice: ${await coinClient.checkBalance(alice)}`);
console.log(`Bob: ${await coinClient.checkBalance(bob)}`);
console.log("");
})();
Loading

0 comments on commit 8eff22d

Please sign in to comment.