# Truffle

트러플은 솔리디티로 작성된 스마트 컨트랙트를 컴파일하고 배포하는 데 사용됩니다. 트러플에 대한 자세한 내용은 다음 사이트를 참조하세요.

* 트러플 스토리지 - <https://github.com/trufflesuite/truffle>
* 트러플 문서 - <https://trufflesuite.com/docs/>

## 1. Truffle 설치

다음 명령을 실행하여 npm을 전역(global)으로 사용할 수 있습니다.

```shell
$ npm install truffle -g
```

## 2. 프로젝트 디렉토리 생성 <a href="#deploying-a-smart-contract-using-truffle" id="deploying-a-smart-contract-using-truffle"></a>

우선, 소스 코드가 위치할 디렉토리를 생성하세요.

```shell
$ mkdir meverse-test
$ cd meverse-test
```

## 3. 트러플 초기화

컨트랙트 배포를 위해 트러플을 초기화하세요.

```shell
$ truffle init
```

## 4. 간단한 솔리디티 스마트 컨트랙트 작성&#x20;

meverse-test/contracts 디렉토리에 MEVerseGreeter.sol을 생성합니다.&#x20;

```shell
$ cd contracts
$ touch MEVerseGreeter.sol
$ vi MEVerseGreeter.sol
```

MEVerseGreeter.sol에 다음 코드를 작성하세요.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.6;
contract Mortal {
    /* 주소 타입의 소유자(owner) 변수 정의 */
    address payable owner;
    /* 이 함수는 초기화 시점에 실행되어 컨트랙트 소유자를 설정합니다 */
    constructor () public { owner = msg.sender; }
    /* 컨트랙트에서 자금을 회수하는 함수 */
    function kill() public payable { if (msg.sender == owner) selfdestruct(owner); }
}

contract MEVerseGreeter is Mortal {
    /* 문자열 타입의 변수 greeting 정의 */
    string greeting;
    /* 이 함수는 컨트랙트가 실행될 때 작동합니다 */
    constructor (string memory _greeting) public {
        greeting = _greeting;
    }
    /* 주(Main) 함수 */
    function greet() public view returns (string memory) {
        return greeting;
    }
}
```

## 5. 마이그레이션(Migration) 스크립트 수정

hdwallet-provider를 활용하여 컨트랙트를 배포합니다. 배포를 하기 위해 library를 설치합니다.

```shell
$ npm install @truffle/hdwallet-provider
```

* *truffle의 **Dashboard**를 활용하여 작성한 컨트랙트도 배포가 가능합니다. Dashboard의 자세한 내용은 하기 사이트를 참고하세요*.

> **Use Truffle Dashboard** : <https://trufflesuite.com/docs/truffle/how-to/use-the-truffle-dashboard/>

truffle-config.js에 MEVerse Testnet network 정보를 수정합니다.

```javascript
// truffle-config.js
const HDWalletProvider = require("@truffle/hdwallet-provider");
...
networks: {
    MEVerseTestnet: {
      provider: () =>
        new HDWalletProvider({
          privateKeys: [
            "adf...583a9", // 컨트랙트를 배포할 계정 private key
          ],
          providerOrUrl: "https://rpc.meversetestnet.io",
        }),
      network_id: 4759, // MEVerse testnet chain id
    }
}
```

## 6. 트러플을 사용하여 스마트 컨트랙트 배포 <a href="#deploying-a-smart-contract-using-truffle" id="deploying-a-smart-contract-using-truffle"></a>

```
$ truffle migrate --network MEVerseTestnet
Compiling your contracts...
===========================
> Compiling ./contracts/MEVerseGreeter.sol
> Artifacts written to /truffle_sample/build/contracts
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang



Starting migrations...
======================
> Network name:    'MEVerseTestnet'
> Network id:      4759
> Block gas limit: 30000000 (0x1c9c380)


1_initial_migration.js
======================

   Deploying 'MEVerseGreeter'
   --------------------------
   > transaction hash:    0xe1f6fad3f5121cb1448750113f25e20228c4b9e800d0a7cda8ca04ff464257f2
   > Blocks: 0            Seconds: 0
   > contract address:    0xeb7A1483E3408Af19231262643672719CcFc6E17
   > block number:        27778152
   > block timestamp:     1668760128889501
   > account:             0x19368fCd2F0EE8d2C788b754F6504FD49de449E7
   > balance:             191907.1
   > gas used:            223381 (0x36895)
   > gas price:           1000 gwei
   > value sent:          0 ETH
   > total cost:          0.223381 ETH


   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:            0.414624 ETH


Summary
=======
> Total deployments:   1
> Final cost:          0.414624 ETH
```

## 7. 배포 확인

배포된 컨트랙트 메서드 실행으로 스마트 컨트렉트가 제대로 배포되었는지 확인할 수 있습니다.

truffle networks 명령어로 배포된 컨트랙트의 네트워크를 확인할 수 있습니다.

```shell
$ truffle networks
Network: MEVerseTestnet (id: 4759)
  MEVerseGreeter: 0xeb7A1483E3408Af19231262643672719CcFc6E17
```

컨트랙트를 배포한 네트워크와 연결하기 위해 다음과 같은 명령어를 사용하면 됩니다.

```shell
$ truffle console --network MEVerseTestnet  
truffle(MEVerseTestnet)> 
```

접속후 인스턴스를 생성하고 인스턴스에서 메서드를 호출해서 동작이 잘 되는지를 확인합니다.

```bash
truffle(development)> let mev = await MEVerseGreeter.deployed()
undefined
truffle(MEVerseTestnet)> mev.greet()
'Hello, MEVerse'
truffle(MEVerseTestnet)> 
```

배포는 Console 화면에서 Contract Address를 확인하고 [MEVerse Testnet Scan](https://testnet.meversescan.io/)에서 트랜잭션 해시값으로 검색하여 확인합니다.

<figure><img src="/files/bijopjcjampnztJMpYW0" alt=""><figcaption><p>Testnet Scan(배포 트랜잭션 해시값으로 조회)</p></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://meversedex.gitbook.io/meverse-dev-docs/meverse-dev-docs-kr/undefined-1/ide-and-tools/truffle.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
