Skip to content

Commit

Permalink
feat: cookbook updates
Browse files Browse the repository at this point in the history
  • Loading branch information
andy-haynes committed Sep 16, 2024
1 parent 53c2d27 commit c230e9b
Show file tree
Hide file tree
Showing 8 changed files with 98 additions and 98 deletions.
4 changes: 4 additions & 0 deletions packages/cookbook/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
"deleteAccessKey": "tsx -e \"import f from './accounts/access-keys/delete-access-key.ts'; f(...process.argv.slice(1));\"",
"deployContract": "tsx -e \"import f from './utils/deploy-contract.ts'; f(...process.argv.slice(1));\"",
"getState": "tsx -e \"import f from './utils/get-state.ts'; f(...process.argv.slice(1));\"",
"getTransactionDetail": "tsx -e \"import f from './transactions/get-tx-detail.ts'; f(...process.argv.slice(1));\"",
"unwrapNear": "tsx -e \"import f from './utils/unwrap-near.ts'; f(...process.argv.slice(1));\"",
"verifySignature": "tsx -e \"import f from './utils/verify-signature.ts'; f(...process.argv.slice(1));\"",
"wrapNear": "tsx -e \"import f from './utils/wrap-near.ts'; f(...process.argv.slice(1));\""
},
"devDependencies": {
Expand All @@ -31,6 +34,7 @@
"@near-js/providers": "workspace:*",
"@near-js/signers": "workspace:*",
"@near-js/transactions": "workspace:*",
"@near-js/utils": "workspace:*",
"build": "workspace:*",
"chalk": "4.1.1",
"homedir": "0.6.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,49 +1,31 @@
const { connect, keyStores } = require("near-api-js");
const path = require("path");
const homedir = require("os").homedir();
import {
getTestnetRpcArchivalProvider,
} from '@near-js/client';

const CREDENTIALS_DIR = ".near-credentials";
// block hash of query start (oldest block)
const START_BLOCK_HASH = "GZ8vKdcgsavkEndkDWHCjuhyqSR2TGnp9VDZbTzd6ufG";
// block hash of query end (newest block)
const END_BLOCK_HASH = "8aEcKhF7N1Jyw84e6vHW6Hzp3Ep7mSXJ6Rvnsy5qGJPF";
// contract ID or account ID you want to find transactions details for
const CONTRACT_ID = "relayer.ropsten.testnet";

const credentialsPath = path.join(homedir, CREDENTIALS_DIR);
const keyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);

// NOTE: we're using the archival rpc to look back in time for a specific set
// of transactions. For a full list of what nodes are available, visit:
// https://docs.near.org/docs/develop/node/intro/types-of-node
const config = {
keyStore,
networkId: "testnet",
nodeUrl: "https://archival-rpc.testnet.near.org",
};

getTransactions(START_BLOCK_HASH, END_BLOCK_HASH, CONTRACT_ID);

async function getTransactions(startBlock, endBlock, accountId) {
const near = await connect(config);
export default async function getTransactions(startBlockHash: string = START_BLOCK_HASH, endBlockHash: string = END_BLOCK_HASH, contractId: string = CONTRACT_ID) {
// initialize testnet RPC provider
const rpcProvider = getTestnetRpcArchivalProvider();

// creates an array of block hashes for given range
const blockArr = [];
let blockHash = endBlock;
let blockHash = endBlockHash;
do {
const currentBlock = await getBlockByID(blockHash);
const currentBlock = await rpcProvider.block({ blockId: blockHash });
blockArr.push(currentBlock.header.hash);
blockHash = currentBlock.header.prev_hash;
console.log("working...", blockHash);
} while (blockHash !== startBlock);
} while (blockHash !== startBlockHash);

// returns block details based on hashes in array
const blockDetails = await Promise.all(
blockArr.map((blockId) =>
near.connection.provider.block({
blockId,
})
)
blockArr.map((blockId) => rpcProvider.block({ blockId }))
);

// returns an array of chunk hashes from block details
Expand All @@ -53,14 +35,14 @@ async function getTransactions(startBlock, endBlock, accountId) {

//returns chunk details based from the array of hashes
const chunkDetails = await Promise.all(
chunkHashArr.map(chunk => near.connection.provider.chunk(chunk))
chunkHashArr.map(chunk => rpcProvider.chunk(chunk))
);

// checks chunk details for transactions
// if there are transactions in the chunk we
// find ones associated with passed accountId
const transactions = chunkDetails.flatMap((chunk) =>
(chunk.transactions || []).filter((tx) => tx.signer_id === accountId)
(chunk.transactions || []).filter((tx) => tx.signer_id === contractId)
);

//creates transaction links from matchingTxs
Expand All @@ -71,11 +53,3 @@ async function getTransactions(startBlock, endBlock, accountId) {
console.log("MATCHING TRANSACTIONS: ", transactions);
console.log("TRANSACTION LINKS: ", txsLinks);
}

async function getBlockByID(blockID) {
const near = await connect(config);
const blockInfoByHeight = await near.connection.provider.block({
blockId: blockID,
});
return blockInfoByHeight;
}
29 changes: 0 additions & 29 deletions packages/cookbook/utils/unwrap-near.js

This file was deleted.

56 changes: 56 additions & 0 deletions packages/cookbook/utils/unwrap-near.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import {
functionCall,
getPlaintextFilesystemSigner,
getTestnetRpcProvider,
view,
} from '@near-js/client';
import { formatNearAmount, parseNearAmount } from '@near-js/utils';
import chalk from 'chalk';
import { join } from 'node:path';
import { homedir } from 'node:os';

// On mainnet it's wrap.near, by the way
const WRAP_NEAR_CONTRACT_ID = "wrap.testnet";

export default async function unwrapNear(accountId: string, unwrapAmount: bigint, wrapContract = WRAP_NEAR_CONTRACT_ID) {
if (!accountId || !unwrapAmount) {
console.log(chalk`{red pnpm unwrapNear -- ACCOUNT_ID UNWRAP_AMOUNT [WRAP_CONTRACT]}`);
return;
}

const credentialsPath = join(homedir(), '.near-credentials');

// initialize testnet RPC provider
const rpcProvider = getTestnetRpcProvider();
// initialize the transaction signer using a pre-existing key for `accountId`
const { signer } = getPlaintextFilesystemSigner({ account: accountId, network: 'testnet', filepath: credentialsPath });

const getStorageBalance = () => view({
account: wrapContract,
method: 'storage_balance_of',
args: { account_id: accountId },
deps: { rpcProvider },
}) as Promise<{ available: string, total: string }>;

const { total: preTotal, available: preAvailable } = (await getStorageBalance()) || {};

await functionCall({
sender: accountId,
receiver: wrapContract,
method: 'near_withdraw',
args: { amount: parseNearAmount(unwrapAmount.toString()) },
deposit: 1n,
deps: {
rpcProvider,
signer,
},
});

const { total: postTotal, available: postAvailable } = await getStorageBalance();
console.log(chalk`{white ------------------------------------------------------------------------ }`);
console.log(chalk`{bold.green RESULTS} {white Unwrapped ${unwrapAmount}yN with ${wrapContract}}`);
console.log(chalk`{white ------------------------------------------------------------------------ }`);
console.log(chalk`{bold.white Starting Balance} {white |} {bold.yellow ${formatNearAmount(preAvailable)} / ${formatNearAmount(preTotal)}}`);
console.log(chalk`{bold.white Ending Balance} {white |} {bold.yellow ${formatNearAmount(postAvailable)} / ${formatNearAmount(postTotal)}}`);
console.log(chalk`{white ------------------------------------------------------------------------ }`);
}
30 changes: 0 additions & 30 deletions packages/cookbook/utils/verify-signature.js

This file was deleted.

22 changes: 22 additions & 0 deletions packages/cookbook/utils/verify-signature.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { getTestnetRpcProvider } from '@near-js/client';
import { KeyType, PublicKey } from '@near-js/crypto';
import { baseDecode } from '@near-js/utils';

const ACCOUNT_ID = 'gornt.testnet';
const TX_HASH = '4tMHzHU5p9dXc4WqopReNZ2TMJxZyu913zK4Fn9nMRoB';

export default async function verifySignature(accountId: string = ACCOUNT_ID, transactionHash: string = TX_HASH) {
// initialize testnet RPC provider
const rpcProvider = getTestnetRpcProvider();

const { transaction: { public_key, signature } } = await rpcProvider.getTransaction({ transactionHash, account: accountId });

const hashBytes = baseDecode(transactionHash);
const publicKeyBytes = baseDecode(public_key.slice('ed25519:'.length));
const signatureBytes = baseDecode(signature.slice('ed25519:'.length));
const publicKey = new PublicKey({ keyType: KeyType.ED25519, data: publicKeyBytes });

const isVerified = publicKey.verify(hashBytes, signatureBytes);

console.log(isVerified);
}
2 changes: 1 addition & 1 deletion packages/cookbook/utils/wrap-near.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export default async function wrapNear(accountId: string, wrapAmount: bigint, wr
receiver: wrapContract,
});

const { total: preTotal, available: preAvailable } = await getStorageBalance();
const { total: preTotal, available: preAvailable } = (await getStorageBalance()) || {};
const _30tgas = BigInt(3e13);
if (!preTotal) {
wrapTransaction.functionCall('storage_deposit', {}, _30tgas, BigInt(1.25e21));
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit c230e9b

Please sign in to comment.