|
| 1 | +import { RPC_Node_URL } from "../../config/rpc_node_url.ts"; |
| 2 | +import { representatives } from "../../config/representatives.ts"; |
| 3 | +import { BigNumber, nanocurrency } from "../../deps.ts"; |
| 4 | +import { |
| 5 | + get_account_info, |
| 6 | + get_account_keys, |
| 7 | + Publish_Block, |
| 8 | + publish_block, |
| 9 | + work_generate, |
| 10 | + xno_to_raw, |
| 11 | +} from "../../mod.ts"; |
| 12 | + |
| 13 | +export type Send_XNO = Publish_Block; |
| 14 | + |
| 15 | +/** |
| 16 | + * |
| 17 | + * @name Send Amount |
| 18 | + * @param {string} sender_private_key |
| 19 | + * @param {string} receiver_address |
| 20 | + * @param {string} amount_xno |
| 21 | + * @param {RPC_Node_URL} rpc_node_url |
| 22 | + * @returns {Send_XNO} |
| 23 | +
|
| 24 | + * @example |
| 25 | + * ```ts |
| 26 | + * import { RPC_Node_URL, send_xno } from './deps.ts'; |
| 27 | + * |
| 28 | + * const sender_private_key = "40C146373BF03EF2D62E067D38A5E6BDE2B511B5C90A99C62B6F7C3D321DDEAC"; |
| 29 | + * const receiver_address = "nano_1trd73o8z76wnnwmuq6y5pe6r396p7m7qf5zufrox9uk3io8foyd8mowgxu3"; |
| 30 | + * const amount_xno = "10.31"; |
| 31 | + * |
| 32 | + * const { error, hash } = await send_xno(sender_private_key, receiver_address, amount_xno, RPC_Node_URL.RAINSTROM); |
| 33 | + * ``` |
| 34 | + */ |
| 35 | +export const send_xno = async ( |
| 36 | + sender_private_key: string, |
| 37 | + receiver_address: string, |
| 38 | + amount_xno: string, |
| 39 | + rpc_node_url: RPC_Node_URL = RPC_Node_URL.RAINSTROM, |
| 40 | +): Promise<Send_XNO> => { |
| 41 | + const { address, private_key } = get_account_keys(sender_private_key); |
| 42 | + const sender_account_info = await get_account_info(address, rpc_node_url); |
| 43 | + |
| 44 | + if ("error" in sender_account_info) { |
| 45 | + return { error: sender_account_info.error }; |
| 46 | + } |
| 47 | + |
| 48 | + const { error, work } = await work_generate( |
| 49 | + sender_account_info.frontier, |
| 50 | + rpc_node_url, |
| 51 | + ); |
| 52 | + |
| 53 | + if (error || !work) return { error }; |
| 54 | + |
| 55 | + const sender = { |
| 56 | + address, |
| 57 | + balance: new BigNumber(sender_account_info.balance), |
| 58 | + frontier: sender_account_info.frontier, |
| 59 | + work: work, |
| 60 | + }; |
| 61 | + |
| 62 | + const amount_to_send_raw = xno_to_raw(amount_xno); |
| 63 | + const balance = (sender.balance).minus(amount_to_send_raw); |
| 64 | + |
| 65 | + if (balance.isGreaterThanOrEqualTo(0)) { |
| 66 | + const block_data: nanocurrency.BlockData = { |
| 67 | + balance: balance.toFixed(), |
| 68 | + link: receiver_address, |
| 69 | + previous: sender.frontier, |
| 70 | + representative: representatives.KRAKEN, |
| 71 | + work: sender.work, |
| 72 | + }; |
| 73 | + |
| 74 | + const { block } = nanocurrency.createBlock(private_key, block_data); |
| 75 | + return await publish_block(block, rpc_node_url); |
| 76 | + } else return { error: "No sufficient balance" }; |
| 77 | +}; |
0 commit comments