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
6import privateKey from "./substrate/privateKey";6import privateKey from "./substrate/privateKey";
7import {7import {
8 deployFlipper,8 deployFlipper,
9 getFlipValue9 getFlipValue,
10 deployTransferContract,
10} from "./util/contracthelpers";11} from "./util/contracthelpers";
12
13import {
14 createCollectionExpectSuccess,
15 createItemExpectSuccess,
16 getGenericResult
17} from "./util/helpers";
18
1119
12chai.use(chaiAsPromised);20chai.use(chaiAsPromised);
23 const initialGetResponse = await getFlipValue(contract, deployer);31 const initialGetResponse = await getFlipValue(contract, deployer);
2432
25 const bob = privateKey("//Bob");33 const bob = privateKey("//Bob");
26 const flip = contract.exec('flip', value, gasLimit);34 const flip = contract.tx.flip(value, gasLimit);
27 await submitTransactionAsync(bob, flip);35 await submitTransactionAsync(bob, flip);
2836
29 const afterFlipGetResponse = await getFlipValue(contract, deployer);37 const afterFlipGetResponse = await getFlipValue(contract, deployer);
41 });49 });
42 });50 });
4351
44 it.skip('Can transfer balance using smart contract.', async () => {52 it('Can transfer NFT using smart contract.', async () => {
45 await usingApi(async api => {53 await usingApi(async api => {
46 // const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);54 const alice = privateKey("//Alice");
47 // const wasm = fs.readFileSync('./src/balance-transfer-contract/calls.wasm');55 const bob = privateKey("//Bob");
48 // const contract = compactAddLength(u8aToU8a(wasm));56
4957 // Prep work
50 // const metadata = JSON.parse(fs.readFileSync('./src/balance-transfer-contract/metadata.json').toString('utf-8'));58 const collectionId = await createCollectionExpectSuccess();
51 // const abi = new Abi(api.registry as any, metadata);59 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
5260 const [contract, deployer] = await deployTransferContract(api);
53 // const alicesPrivateKey = privateKey('//Alice');61 const tokenBefore: any = await api.query.nft.nftItemList(collectionId, tokenId);
5462
55 // const contractHash = await deployContract(api, contract, alicesPrivateKey);63 // Transfer
5664 const transferTx = contract.tx.transfer(value, gasLimit, bob.address, collectionId, tokenId, 1);
57 // // const args = abi.constructors[0]();65 const events = await submitTransactionAsync(alice, transferTx);
58 // const instanceAccountId = await instantiateContract(api, contractHash, /*args,*/ alicesPrivateKey);66 const result = getGenericResult(events);
59 // const contractInstance = new ContractPromise(api, abi, instanceAccountId);67 const tokenAfter: any = await api.query.nft.nftItemList(collectionId, tokenId);
60 // const bob = new GenericAccountId(api.registry, bobsPublicKey);68
6169 // tslint:disable-next-line:no-unused-expression
62 // const transfer = contractInstance.exec('balance_transfer', 0, 1000000000000n, [bob, new u128(api.registry, 1000000)]);70 expect(result.success).to.be.true;
63 // await submitTransactionAsync(alicesPrivateKey, transfer);71 expect(tokenBefore.Owner.toString()).to.be.equal(alice.address);
6472 expect(tokenAfter.Owner.toString()).to.be.equal(bob.address);
65 // const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);
66
67 // expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;
68 // expect(bobsBalanceAfter > bobsBalanceBefore).to.be.true;
69 });73 });
70 });74 });
71});75});
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];
+}