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
1414
15describe('Integration Test addToContractWhiteList', () => {15describe('Integration Test addToContractWhiteList', () => {
1616
17 it.only(`Add an address to a contract white list`, async () => {17 it(`Add an address to a contract white list`, async () => {
18 await usingApi(async api => {18 await usingApi(async api => {
19 const bob = privateKey("//Bob");19 const bob = privateKey("//Bob");
20 const [contract, deployer] = await deployFlipper(api);20 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
--- a/tests/src/util/contracthelpers.ts
+++ b/tests/src/util/contracthelpers.ts
@@ -37,21 +37,11 @@
 function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {
   return new Promise<any>(async (resolve, reject) => {
     const initValue = true;
-    const constructorIndex = 0;
-
-    // const unsub = await blueprint
-    // .createContract(constructorIndex, { gasLimit: gasLimit, salt: null, value: endowment }, initValue)
 
-    // const unsub = await blueprint.tx
-    // .new({ gasLimit: gasLimit, salt: null, value: endowment }, initValue)
-
     const unsub = await blueprint.tx
     .new(endowment, gasLimit, initValue)
     .signAndSend(alice, (result) => {
       if (result.status.isInBlock || result.status.isFinalized) {
-
-        console.log("Contract deployed: ", result);
-
         unsub();
         resolve(result);
       }
@@ -67,7 +57,7 @@
   const keyring = new Keyring({ type: 'sr25519' });
   const alice = keyring.addFromUri(`//Alice`);
   let amount = new BigNumber(endowment);
-  amount = amount.plus(1e15);
+  amount = amount.plus(100e15);
   const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());
   await submitTransactionAsync(alice, tx);
 
@@ -101,3 +91,32 @@
   }
   return (result.result.asOk.data[0] == 0x00) ? false : true;
 }
+
+function instantiateTransferContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {
+  return new Promise<any>(async (resolve, reject) => {
+    const unsub = await blueprint.tx
+    .default(endowment, gasLimit)
+    .signAndSend(alice, (result) => {
+      if (result.status.isInBlock || result.status.isFinalized) {
+        unsub();
+        resolve(result);
+      }
+    });    
+  });
+}
+
+export async function deployTransferContract(api: ApiPromise): Promise<[Contract, IKeyringPair]> {
+  const metadata = JSON.parse(fs.readFileSync('./src/transfer_contract/metadata.json').toString('utf-8'));
+  const abi = new Abi(metadata);
+
+  const deployer = await prepareDeployer(api);
+
+  const wasm = fs.readFileSync('./src/transfer_contract/nft_transfer.wasm');
+
+  const code = new CodePromise(api, abi, wasm);
+
+  const blueprint = await deployBlueprint(deployer, code);
+  const contract = (await instantiateTransferContract(deployer, blueprint))['contract'] as Contract;
+
+  return [contract, deployer];
+}