git.delta.rocks / unique-network / refs/commits / 135789fda83b

difftreelog

Add test to transfer NFT using smart contract

Greg Zaitsev2021-02-01parent: #b5214e3.patch.diff
in: master

5 files changed

modifiedtests/src/addToContractWhiteList.test.tsdiffbeforeafterboth
--- a/tests/src/addToContractWhiteList.test.ts
+++ b/tests/src/addToContractWhiteList.test.ts
@@ -14,7 +14,7 @@
 
 describe('Integration Test addToContractWhiteList', () => {
 
-  it.only(`Add an address to a contract white list`, async () => {
+  it(`Add an address to a contract white list`, async () => {
     await usingApi(async api => {
       const bob = privateKey("//Bob");
       const [contract, deployer] = await deployFlipper(api);
modifiedtests/src/contracts.test.tsdiffbeforeafterboth
--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -6,9 +6,17 @@
 import privateKey from "./substrate/privateKey";
 import {
   deployFlipper,
-  getFlipValue
+  getFlipValue,
+  deployTransferContract,
 } from "./util/contracthelpers";
 
+import {
+  createCollectionExpectSuccess,
+  createItemExpectSuccess,
+  getGenericResult
+} from "./util/helpers";
+
+
 chai.use(chaiAsPromised);
 const expect = chai.expect;
 
@@ -23,7 +31,7 @@
       const initialGetResponse = await getFlipValue(contract, deployer);
 
       const bob = privateKey("//Bob");
-      const flip = contract.exec('flip', value, gasLimit);
+      const flip = contract.tx.flip(value, gasLimit);
       await submitTransactionAsync(bob, flip);
 
       const afterFlipGetResponse = await getFlipValue(contract, deployer);
@@ -41,31 +49,27 @@
     });
   });
 
-  it.skip('Can transfer balance using smart contract.', async () => {
+  it('Can transfer NFT using smart contract.', async () => {
     await usingApi(async api => {
-      // const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);
-      // const wasm = fs.readFileSync('./src/balance-transfer-contract/calls.wasm');
-      // const contract = compactAddLength(u8aToU8a(wasm));
+      const alice = privateKey("//Alice");
+      const bob = privateKey("//Bob");
 
-      // const metadata = JSON.parse(fs.readFileSync('./src/balance-transfer-contract/metadata.json').toString('utf-8'));
-      // const abi = new Abi(api.registry as any, metadata);
-
-      // const alicesPrivateKey = privateKey('//Alice');
+      // Prep work
+      const collectionId = await createCollectionExpectSuccess();
+      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+      const [contract, deployer] = await deployTransferContract(api);
+      const tokenBefore: any = await api.query.nft.nftItemList(collectionId, tokenId);
+      
+      // Transfer
+      const transferTx = contract.tx.transfer(value, gasLimit, bob.address, collectionId, tokenId, 1);
+      const events = await submitTransactionAsync(alice, transferTx);
+      const result = getGenericResult(events);
+      const tokenAfter: any = await api.query.nft.nftItemList(collectionId, tokenId);
 
-      // const contractHash = await deployContract(api, contract, alicesPrivateKey);
-
-      // // const args = abi.constructors[0]();
-      // const instanceAccountId = await instantiateContract(api, contractHash, /*args,*/ alicesPrivateKey);
-      // const contractInstance = new ContractPromise(api, abi, instanceAccountId);
-      // const bob = new GenericAccountId(api.registry, bobsPublicKey);
-
-      // const transfer = contractInstance.exec('balance_transfer', 0, 1000000000000n, [bob, new u128(api.registry, 1000000)]);
-      // await submitTransactionAsync(alicesPrivateKey, transfer);
-
-      // const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);
-
-      // expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;
-      // expect(bobsBalanceAfter > bobsBalanceBefore).to.be.true;
+      // tslint:disable-next-line:no-unused-expression
+      expect(result.success).to.be.true;
+      expect(tokenBefore.Owner.toString()).to.be.equal(alice.address);
+      expect(tokenAfter.Owner.toString()).to.be.equal(bob.address);
     });
   });
 });
addedtests/src/transfer_contract/metadata.jsondiffbeforeafterboth
--- /dev/null
+++ b/tests/src/transfer_contract/metadata.json
@@ -0,0 +1,131 @@
+{
+  "metadataVersion": "0.1.0",
+  "source": {
+    "hash": "0xfbbc0729acefed9d99f93f6cbb751d12e317958fd0fe183f5781329b37f1bf6e",
+    "language": "ink! 3.0.0-rc2",
+    "compiler": "rustc 1.51.0-nightly"
+  },
+  "contract": {
+    "name": "nft_transfer",
+    "version": "0.1.0",
+    "authors": [
+      "[Greg Zaitsev] <[your_email]>"
+    ]
+  },
+  "spec": {
+    "constructors": [
+      {
+        "args": [],
+        "docs": [
+          "Default Constructor",
+          "",
+          "Constructors can delegate to other constructors."
+        ],
+        "name": [
+          "default"
+        ],
+        "selector": "0x6a3712e2"
+      }
+    ],
+    "docs": [],
+    "events": [],
+    "messages": [
+      {
+        "args": [
+          {
+            "name": "recipient",
+            "type": {
+              "displayName": [
+                "AccountId"
+              ],
+              "type": 1
+            }
+          },
+          {
+            "name": "collection_id",
+            "type": {
+              "displayName": [
+                "u32"
+              ],
+              "type": 4
+            }
+          },
+          {
+            "name": "token_id",
+            "type": {
+              "displayName": [
+                "u32"
+              ],
+              "type": 4
+            }
+          },
+          {
+            "name": "amount",
+            "type": {
+              "displayName": [
+                "u128"
+              ],
+              "type": 5
+            }
+          }
+        ],
+        "docs": [
+          " Transfer one NFT token"
+        ],
+        "mutates": true,
+        "name": [
+          "transfer"
+        ],
+        "payable": false,
+        "returnType": null,
+        "selector": "0xfae3a09d"
+      }
+    ]
+  },
+  "storage": {
+    "struct": {
+      "fields": []
+    }
+  },
+  "types": [
+    {
+      "def": {
+        "composite": {
+          "fields": [
+            {
+              "type": 2
+            }
+          ]
+        }
+      },
+      "path": [
+        "ink_env",
+        "types",
+        "AccountId"
+      ]
+    },
+    {
+      "def": {
+        "array": {
+          "len": 32,
+          "type": 3
+        }
+      }
+    },
+    {
+      "def": {
+        "primitive": "u8"
+      }
+    },
+    {
+      "def": {
+        "primitive": "u32"
+      }
+    },
+    {
+      "def": {
+        "primitive": "u128"
+      }
+    }
+  ]
+}
\ No newline at end of file
addedtests/src/transfer_contract/nft_transfer.wasmdiffbeforeafterboth

binary blob — no preview

modifiedtests/src/util/contracthelpers.tsdiffbeforeafterboth
before · tests/src/util/contracthelpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import chai from "chai";7import chaiAsPromised from 'chai-as-promised';8import { submitTransactionAsync } from "../substrate/substrate-api";9import fs from "fs";10import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";11import { IKeyringPair } from "@polkadot/types/types";12import { ApiPromise, Keyring } from "@polkadot/api";1314chai.use(chaiAsPromised);15const expect = chai.expect;16import { BigNumber } from 'bignumber.js';17import { findUnusedAddress } from '../util/helpers';1819const value = 0;20const gasLimit = '200000000000';21const endowment = '100000000000000000';2223function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {24  return new Promise<Blueprint>(async (resolve, reject) => {25    const unsub = await code26      .createBlueprint()27      .signAndSend(alice, (result) => {28        if (result.status.isInBlock || result.status.isFinalized) {29          // here we have an additional field in the result, containing the blueprint30          resolve(result.blueprint);31          unsub();32        }33      })34  });35}3637function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {38  return new Promise<any>(async (resolve, reject) => {39    const initValue = true;40    const constructorIndex = 0;4142    // const unsub = await blueprint43    // .createContract(constructorIndex, { gasLimit: gasLimit, salt: null, value: endowment }, initValue)4445    // const unsub = await blueprint.tx46    // .new({ gasLimit: gasLimit, salt: null, value: endowment }, initValue)4748    const unsub = await blueprint.tx49    .new(endowment, gasLimit, initValue)50    .signAndSend(alice, (result) => {51      if (result.status.isInBlock || result.status.isFinalized) {5253        console.log("Contract deployed: ", result);5455        unsub();56        resolve(result);57      }58    });    59  });60}6162async function prepareDeployer(api: ApiPromise) {63  // Find unused address64  const deployer = await findUnusedAddress(api);6566  // Transfer balance to it67  const keyring = new Keyring({ type: 'sr25519' });68  const alice = keyring.addFromUri(`//Alice`);69  let amount = new BigNumber(endowment);70  amount = amount.plus(1e15);71  const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());72  await submitTransactionAsync(alice, tx);7374  return deployer;75}7677export async function deployFlipper(api: ApiPromise): Promise<[Contract, IKeyringPair]> {78  const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));79  const abi = new Abi(metadata);8081  const deployer = await prepareDeployer(api);8283  const wasm = fs.readFileSync('./src/flipper/flipper.wasm');8485  const code = new CodePromise(api, abi, wasm);8687  const blueprint = await deployBlueprint(deployer, code);88  const contract = (await deployContract(deployer, blueprint))['contract'] as Contract;8990  const initialGetResponse = await getFlipValue(contract, deployer);91  expect(initialGetResponse).to.be.true;9293  return [contract, deployer];94}9596export async function getFlipValue(contract: Contract, deployer: IKeyringPair) {97  const result = await contract.query.get(deployer.address, value, gasLimit);9899  if(!result.result.isOk) {100    throw `Failed to get flipper value`;101  }102  return (result.result.asOk.data[0] == 0x00) ? false : true;103}
after · tests/src/util/contracthelpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import chai from "chai";7import chaiAsPromised from 'chai-as-promised';8import { submitTransactionAsync } from "../substrate/substrate-api";9import fs from "fs";10import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";11import { IKeyringPair } from "@polkadot/types/types";12import { ApiPromise, Keyring } from "@polkadot/api";1314chai.use(chaiAsPromised);15const expect = chai.expect;16import { BigNumber } from 'bignumber.js';17import { findUnusedAddress } from '../util/helpers';1819const value = 0;20const gasLimit = '200000000000';21const endowment = '100000000000000000';2223function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {24  return new Promise<Blueprint>(async (resolve, reject) => {25    const unsub = await code26      .createBlueprint()27      .signAndSend(alice, (result) => {28        if (result.status.isInBlock || result.status.isFinalized) {29          // here we have an additional field in the result, containing the blueprint30          resolve(result.blueprint);31          unsub();32        }33      })34  });35}3637function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {38  return new Promise<any>(async (resolve, reject) => {39    const initValue = true;4041    const unsub = await blueprint.tx42    .new(endowment, gasLimit, initValue)43    .signAndSend(alice, (result) => {44      if (result.status.isInBlock || result.status.isFinalized) {45        unsub();46        resolve(result);47      }48    });    49  });50}5152async function prepareDeployer(api: ApiPromise) {53  // Find unused address54  const deployer = await findUnusedAddress(api);5556  // Transfer balance to it57  const keyring = new Keyring({ type: 'sr25519' });58  const alice = keyring.addFromUri(`//Alice`);59  let amount = new BigNumber(endowment);60  amount = amount.plus(100e15);61  const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());62  await submitTransactionAsync(alice, tx);6364  return deployer;65}6667export async function deployFlipper(api: ApiPromise): Promise<[Contract, IKeyringPair]> {68  const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));69  const abi = new Abi(metadata);7071  const deployer = await prepareDeployer(api);7273  const wasm = fs.readFileSync('./src/flipper/flipper.wasm');7475  const code = new CodePromise(api, abi, wasm);7677  const blueprint = await deployBlueprint(deployer, code);78  const contract = (await deployContract(deployer, blueprint))['contract'] as Contract;7980  const initialGetResponse = await getFlipValue(contract, deployer);81  expect(initialGetResponse).to.be.true;8283  return [contract, deployer];84}8586export async function getFlipValue(contract: Contract, deployer: IKeyringPair) {87  const result = await contract.query.get(deployer.address, value, gasLimit);8889  if(!result.result.isOk) {90    throw `Failed to get flipper value`;91  }92  return (result.result.asOk.data[0] == 0x00) ? false : true;93}9495function instantiateTransferContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {96  return new Promise<any>(async (resolve, reject) => {97    const unsub = await blueprint.tx98    .default(endowment, gasLimit)99    .signAndSend(alice, (result) => {100      if (result.status.isInBlock || result.status.isFinalized) {101        unsub();102        resolve(result);103      }104    });    105  });106}107108export async function deployTransferContract(api: ApiPromise): Promise<[Contract, IKeyringPair]> {109  const metadata = JSON.parse(fs.readFileSync('./src/transfer_contract/metadata.json').toString('utf-8'));110  const abi = new Abi(metadata);111112  const deployer = await prepareDeployer(api);113114  const wasm = fs.readFileSync('./src/transfer_contract/nft_transfer.wasm');115116  const code = new CodePromise(api, abi, wasm);117118  const blueprint = await deployBlueprint(deployer, code);119  const contract = (await instantiateTransferContract(deployer, blueprint))['contract'] as Contract;120121  return [contract, deployer];122}