# EosJS API 사용

# EosJS API 사용

안녕하세요. 권동준 입니다.
 이전에 EOSJS 시작하기에서 간단하게 EOSJS를 사용하는 방법을 해봤습니다. 이번에는 EosJs에서 제공하는 api 중에 자주 쓰는 api를 소개하고 테스트 할 수 있게 진행을 하려고 합니다. 

> api 목록을 보기를 원하시면 [여기](https://github.com/EOSIO/eosjs-api/blob/master/docs/api.md#eos--object)를 확인해 보시면 됩니다. 



#### 시작하기에 앞서 준비하기

모든 코드를 직접 사용 해볼 수 있게 할 예정입니다. 그렇게 하기 위해서는 준비가 필요합니다. 

준비 사항은 아래와 같습니다.

1. nodeJs
2. eosJs

위의 2개를 설치하고 javascript 파일 가장 위에 아래와 같이 넣어주세요.

```javascript
const Eos = require('eosjs');

const config = {
    expireInSeconds: 60,
    broadcast: true,
    debug: false,
    sign: true,
    // mainNet bp endpoint
    httpEndpoint: 'https://api.eosnewyork.io',
    // mainNet chainId
    chainId: 'aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906',
};

const eos = Eos(config);
```

이렇게 넣고 나서 아래의 api 예제를 직접 코딩하고 nodeJs로 javascript를 실행하면 값이 나옵니다.

> Bp Endpoint마다 응답속도 혹은 신뢰도가 각각 다르게 때문에 본인에 가장 맞는 bp를 사용하기를 권장합니다.



#### getBlock(blockNumOrId)

해당 블록의 정보를 가지고 올 수 있습니다.

params:

| param           | 설명                   |
| --------------- | ---------------------- |
| block_num_or_id | 블록의 아이디나 number |

Code:

```javascript
// Promise
eos.getBlock(1).then(result => console.log(result)).catch(error => console.error(error));

// callback
eos.getBlock(1, (error, result) => console.log(error, result));

// Parameters object
eos.getBlock({block_num_or_id: 1}).then(console.log);
```

결과 값: 

```json
{ timestamp: '2018-06-08T08:08:08.500',
  producer: '',
  confirmed: 1,
  previous:
   '0000000000000000000000000000000000000000000000000000000000000000',
  transaction_mroot:
   '0000000000000000000000000000000000000000000000000000000000000000',
  action_mroot:
   'aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906',
  schedule_version: 0,
  new_producers: null,
  header_extensions: [],
  producer_signature:
   'SIG_K1_111111111111111111111111111111111111111111111111111111111111111116uk5ne',
  transactions: [],
  block_extensions: [],
  id:
   '00000001405147477ab2f5f51cda427b638191c66d2c59aa392d5c2c98076cb0',
  block_num: 1,
  ref_block_prefix: 4126519930 }
```

해당 블록에서 어떠한 일을 했는지 보기 위해서는 transactions를 보면 됩니다. 

transactions를 보기 위해 아래와 같이 한번 같이 해보시죠.

```javascript
[ { status: 'executed',
    cpu_usage_us: 1170,
    net_usage_words: 40,
    trx:
     { id:
        '8a29bfa66850b7d4a2b0b62173a24c5dfe4dbd7b39c211df6309d02a85374960',
       signatures: [Array],
       compression: 'none',
       packed_context_free_data: '',
       context_free_data: [],
       packed_trx:
        '9051595bad38f016a289000000000100a6823403ea3055000000572d3ccdcd0110e0a53cab294d7600000000a8ed3232dd0110e0a53cab294d76a0986af64b96bc65010000000000000004454f5300000000bb01496e74726f647563696e67204954414d204e6574776f726b2c20616e20454f532d426173656420444150502050726f6a656374206f6e20426c6f636b636861696e2047616d696e6720506c6174666f726d20666f722061205472616e73706172656e742047616d696e672045636f73797374656d2e202d2d576562736974653a2068747470733a2f2f6974616d2e67616d65732f656e202d2d54656c656772616d3a2068747470733a2f2f742e6d652f6974616d6e6574776f726b00',
       transaction: [Object] } }
 ]
```

위와 같은 값으로 주며 저기에서도 transaction를 보면 actions가 있으며 그걸 보면 이 블록에서 어떤일들을 했는지 더욱 깊게 볼 수 있습니다.



### getAccount(accountName)

Eos계정의 정보를 가지고 올때 사용합니다.

Params:

| Param        | 설명            |
| ------------ | --------------- |
| account_name | eos 계정의 이름 |

Code:

```javascript
// Promise
eos.getAccount('itamnetwork1')
    .then(result => console.log(result))
    .catch(error => console.error(error));

// callback
eos.getAccount('itamnetwork1', (error, result) => console.log(error, result));

// Parameters object
eos.getAccount({account_name: 'itamnetwork1'})
    .then(result => console.log(result))
    .catch(error => console.error(error));
```

결과 값

```json
{ account_name: 'itamnetwork1',
  head_block_num: 8516805,
  head_block_time: '2018-07-30T07:34:52.500',
  privileged: false,
  last_code_update: '1970-01-01T00:00:00.000',
  created: '2018-07-09T02:24:58.500',
  core_liquid_balance: '12.6131 EOS',
  ram_quota: 14976,
  net_weight: 201000,
  cpu_weight: 10401000,
  net_limit: { used: 1679786, available: 11108657, max: 12788443 },
  cpu_limit: { used: 7950353, available: 6356380, max: 14306733 },
  ram_usage: 10934,
  permissions:
   [ { perm_name: 'active', parent: 'owner', required_auth: [Object] },
     { perm_name: 'owner', parent: '', required_auth: [Object] } ],
  total_resources:
   { owner: 'itamnetwork1',
     net_weight: '20.1000 EOS',
     cpu_weight: '1040.1000 EOS',
     ram_bytes: 14976 },
  self_delegated_bandwidth:
   { from: 'itamnetwork1',
     to: 'itamnetwork1',
     net_weight: '0.1000 EOS',
     cpu_weight: '0.1000 EOS' },
  refund_request: null,
  voter_info:
   { owner: 'itamnetwork1',
     proxy: '',
     producers: [],
     staked: 4000,
     last_vote_weight: '0.00000000000000000',
     proxied_vote_weight: '0.00000000000000000',
     is_proxy: 0 } }
```

위의 결과값중에 다 중요하지만 몇개만 설명을 하려 합니다.

1. account_name
   누구나 다 알다 싶이 eos account name 입니다.

2. ram_quota

   내가 보유한 RAM 입니다. 단위는 byte입니다.

3. net_limit

   해당 계정이 가지고 있는 총 net, 사용 가능한 net, 사용한 net을 나타냅니다. 단위는 byte입니다.

4. cpu_limit

   해당 계정이 가지고 있는 총 cpu, 사용 가능한 cpu, 사용한 cpu을 나타냅니다. 단위는 us 입니다.

5. ram_usage

   해당 계정이 사용한 RAM 입니다 단위는 byte입니다.

6. total_resources
   나에게 할당된 리소스의 eos를 보여줍니다. (누군가가 나에게 delegated한 것도 포함됩니다.)

7. self_delegated_bandwidth
   내가 내 자신에게 delegated한 정보 입니다.

8. voter_info

   투표에 대한 정보입니다. 여기에서 눈여겨 봐야될 부분은 staked입니다. 이부분은 현재 내가 staked 한 부분인데요. 좀더 자세히 설명한다면 내가 스스로 내 자신에게 delegated한 부분과 누군가에서 delegated한 부분을 포함한 값입니다.



### getKeyAccounts(publicKey)

public key에 해당하는 account들을 가지고 옵니다.

Params:

| Param      | 설명             |
| ---------- | ---------------- |
| public_key | EOS의 public key |

Code:

```javascript
// Promise
eos.getKeyAccounts('EOS6S6C5ExCM7VHGdmG5h6VREVJEC33bpMJtLucwhyByPmzB58KW5')
    .then(result => console.log(result))
    .catch(error => console.error(error));

// callback
eos.getKeyAccounts('EOS6S6C5ExCM7VHGdmG5h6VREVJEC33bpMJtLucwhyByPmzB58KW5',
    (error, result) => console.log(error, result));

// Parameters object
eos.getKeyAccounts({public_key: 'EOS6S6C5ExCM7VHGdmG5h6VREVJEC33bpMJtLucwhyByPmzB58KW5'})
    .then(console.log);
```

결과값:

```json
{ account_names: [ 'itamnetwork1' ] }
```

EOS의 public key 한개로 여러 account를 만들수 있습니다. 그렇게 때문에 account_name의 값이 string으로 이루어진 array 입니다.



### getCurrencyBalance(code, account, symbol)

code의 symbol에 해당하는 Token을 가지고 옵니다. 

Params:

| Param   | 설명                                                         |
| ------- | ------------------------------------------------------------ |
| code    | 컨트렉트 명 혹은 해당 컨트렉트가 있는 account명을 말합니다.<br />ex) eosio.token, therealkarma 등등 |
| account | 조회할 EOS의 계정명 입니다.                                  |
| symbol  | Token의 symbol 입니다. 이부분은 필수값이 아닌 옵션 값입니다. |

Code:

```javascript
// Promise
eos.getCurrencyBalance('eosio.token', 'itamnetwork1', 'EOS')
    .then(result => console.log(result))
    .catch(error => console.error(error));

// callback
eos.getCurrencyBalance('eosio.token', 'itamnetwork1', 'EOS',
    (error, result) => console.log(error, result));

// Parameters object
eos.getCurrencyBalance({account: 'itamnetwork1', code: 'eosio.token', symbol: 'EOS'})
    .then(console.log);
```

결과값:

```json
[ '12.6131 EOS' ]
```

결과 값을 보면 string형식의 array가 나옵니다. 이유는 해당 컨트렉트안에 여러 symbol을 가진 token들이 있을수 있기 때문입니다. EOS 테스트넷인 정글넷을 보면 symbol을 제외하고 eosio.token을 조회하면 2개의 token들을 볼수 있습니다.



### getCurrencyStats(code, symbol)

symbol에 해당하는  Token의 정보를 가지고 옵니다.

Params:

| Param  | 설명                                                         |
| ------ | ------------------------------------------------------------ |
| code   | 컨트렉트 명 혹은 해당 컨트렉트가 있는 account명을 말합니다.<br />ex) eosio.token, therealkarma 등등 |
| symbol | Token의 symbol 입니다.                                       |

Code:

```javascript
// Promise
eos.getCurrencyStats('eosio.token', 'EOS')
    .then(result => console.log(result))
    .catch(error => console.error(error));

// callback
eos.getCurrencyStats('eosio.token', 'EOS',
    (error, result) => console.log(error, result));

// Parameters object
eos.getCurrencyStats({code: 'eosio.token', symbol: 'EOS'})
    .then(console.log);
```

결과값:

```json
{ EOS:
   { supply: '1006148640.3388 EOS',
     max_supply: '10000000000.0000 EOS',
     issuer: 'eosio' } }
```

결과값에 대한 설명은 아래와 같습니다.

1. supply
   현재 공급된 토큰의 갯수 입니다.

2. max_supply

   총 토큰의 갯수 입니다.

3. issuer
   발행자 입니다.



## 마무리하며

자주 쓰는 api들중 5개를 소개하는 시간을 가지게 되었습니다. 아직 더 많은 api들이 있고 다음 블로그에 이어서 많이 쓰는 api들에 대해서 연재할 계획입니다. 감사합니다.



> 해당 예제는 [github](https://github.com/ITAMNETWORK/eosjs-api-example)에서 확인 하실 수 있습니다.

해당 게시글은 저의 블로그 혹은 itamnetwork 블로그에서 동일하게 확인 하실수 있습니다.
