From 392672a5a787932e83e6db279be78210e6156c22 Mon Sep 17 00:00:00 2001 From: Michael Vines Date: Thu, 23 Aug 2018 16:39:52 -0700 Subject: [PATCH] Implement requestAirdrop --- web3.js/src/connection.js | 21 ++++++++++++++++----- web3.js/test/connection.test.js | 13 +++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/web3.js/src/connection.js b/web3.js/src/connection.js index 756c40545f..1f046314d3 100644 --- a/web3.js/src/connection.js +++ b/web3.js/src/connection.js @@ -16,9 +16,9 @@ export type TransactionSignature = string; /** * @typedef {string} TransactionId */ -export type TransactionId= string; +export type TransactionId = string; -type RpcRequest = (methodName: string, args: Array) => any; +type RpcRequest = (methodName: string, args: Array) => any; function createRpcRequest(url): RpcRequest { const server = jayson( @@ -88,6 +88,12 @@ const GetFinalityRpcResult = struct({ error: 'any?', result: 'number?', }); +const RequestAirdropRpcResult = struct({ + jsonrpc: struct.literal('2.0'), + id: 'string', + error: 'any?', + result: 'boolean?', +}); function sleep(duration = 0) { return new Promise((accept) => { @@ -158,9 +164,14 @@ export class Connection { return Number(res.result); } - async requestAirdrop(account: Account, amount: number): Promise { - console.log(`TODO: airdrop ${amount} to ${account.publicKey}`); - await sleep(500); // TODO + async requestAirdrop(to: PublicKey, amount: number): Promise { + const unsafeRes = await this._rpcRequest('requestAirdrop', [to, amount]); + const res = RequestAirdropRpcResult(unsafeRes); + if (res.error) { + throw new Error(res.error.message); + } + assert(typeof res.result !== 'undefined'); + assert(res.result); } async sendTokens(from: Account, to: PublicKey, amount: number): Promise { diff --git a/web3.js/test/connection.test.js b/web3.js/test/connection.test.js index 0331f7879e..f5ed3c62d8 100644 --- a/web3.js/test/connection.test.js +++ b/web3.js/test/connection.test.js @@ -42,4 +42,17 @@ test.skip('get finality', async () => { expect(finality).toBeGreaterThanOrEqual(0); }); +test.skip('request airdrop', async () => { + const account = new Account(); + const connection = new Connection(url); + + await Promise.all([ + connection.requestAirdrop(account.publicKey, 40), + connection.requestAirdrop(account.publicKey, 2), + ]); + + const balance = await connection.getBalance(account.publicKey); + expect(balance).toBe(42); +}); +