본문으로 건너뛰기

동전 던지기

동전 던지기는 플레이어가 동전 던지기의 결과를 추측하는 게임입니다. 이는 난수를 구현하는 가장 간단한 컨트랙트 중 하나입니다.

img


게임 시작하기

예제를 시작하는 두 가지 옵션이 있습니다.

  1. 권장: Gitpod(웹 기반 대화형 환경)를 통해 앱 사용
  2. Clone the project locally.
GitpodClone locally
Open in Gitpodhttps://github.com/near-examples/coin-flip-examples.git

Gitpod를 선택하면 새 브라우저 창이 코드와 함께 자동으로 열립니다. 잠시 기다리면 프론트엔드가 팝업됩니다(팝업 창이 차단되지 않았는지 확인).

If you are running the app locally, you should build and deploy a contract (JavaScript or Rust version) and a client manually.


게임과 상호 작용하기

계속해서 NEAR 계정으로 로그인하십시오. 계정이 없는 경우 즉시 만들 수 있습니다. 로그인한 후 tailsheads 버튼을 통해 다음 동전 던지기 결과를 추측해 보세요.

img 게임의 프론트엔드


dApp의 구조

이제 dApp이 무엇을 하는지 이해했으므로 그 구조를 자세히 살펴보겠습니다.

  1. 프론트엔드 코드는 /frontend 폴더에 있습니다
  2. The smart contract code in Rust is in the /contract-rs folder.
  3. The smart contract code in JavaScript is in the /contract-ts folder.
노트

Both Rust and JavaScript versions of the contract implement the same functionality.

컨트랙트

컨트랙트는 flip_coinpoints_of의 두 가지 메서드를 가지고 있습니다.

contract-ts/src/contract.ts
loading...

프론트엔드

프론트엔드는 하나의 HTML 파일(/index.html)로 구성됩니다. 이 파일은 화면에 표시되는 구성 요소를 정의합니다.

웹사이트의 로직은 /assets/js/index.js에 존재하며 wallet를 통해 컨트랙트와 통신합니다. 다음 코드에서 /assets/js/index.js를 확인할 수 있습니다.

frontend/index.js
loading...

위 코드에서, 앱이 시작될 때 사용자가 이미 로그인되어 있는지 확인하고 signedInFlow() 또는 signedOutFlow()를 실행함을 알 수 있습니다.


Testing

스마트 컨트랙트를 작성할 때 모든 메서드를 철저하게 테스트하는 것이 매우 중요합니다. In this project you have integration tests. Before digging into them, go ahead and perform the tests present in the dApp through the command yarn test for the JavaScript version, or ./test.sh for the Rust version.

통합 테스트

Integration tests can be written in both Rust and JavaScript. 이는 자동으로 컨트랙트를 배포하고, 메서드를 실행합니다. 이러한 방식으로 통합 테스트는 현실적인 시나리오에서 사용자의 상호 작용을 시뮬레이션합니다. You will find the integration tests for the coin-flip in contract-ts/sandbox-ts (for the JavaScript contract) and contract-rs/tests (for the Rust contract).

contract-ts/sandbox-ts/main.ava.ts
loading...

A Note On Randomness

Randomness in the blockchain is a complex subject. 그것에 대해 읽고 조사하는 것이 좋습니다. You can start with our security page on it.

Versioning for this article

At the time of this writing, this example works with the following versions:

  • near-cli: 4.0.13
  • node: 18.19.1
  • rustc: 1.77.0
Was this page helpful?