difftreelog
Add test to transfer NFT using smart contract
in: master
5 files changed
tests/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);
tests/src/contracts.test.tsdiffbeforeafterboth1import chai from "chai";2import chaiAsPromised from 'chai-as-promised';3import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";4import fs from "fs";5import { Abi, ContractPromise as Contract } from "@polkadot/api-contract";6import privateKey from "./substrate/privateKey";7import {8 deployFlipper,9 getFlipValue10} from "./util/contracthelpers";1112chai.use(chaiAsPromised);13const expect = chai.expect;1415const value = 0;16const gasLimit = 3000n * 1000000n;17const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';1819describe('Contracts', () => {20 it(`Can deploy smart contract Flipper, instantiate it and call it's get and flip messages.`, async () => {21 await usingApi(async api => {22 const [contract, deployer] = await deployFlipper(api);23 const initialGetResponse = await getFlipValue(contract, deployer);2425 const bob = privateKey("//Bob");26 const flip = contract.exec('flip', value, gasLimit);27 await submitTransactionAsync(bob, flip);2829 const afterFlipGetResponse = await getFlipValue(contract, deployer);30 expect(afterFlipGetResponse).not.to.be.eq(initialGetResponse, 'Flipping should change value.');31 });32 });3334 it('Can initialize contract instance', async () => {35 await usingApi(async (api) => {36 const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));37 const abi = new Abi(metadata);38 const newContractInstance = new Contract(api, abi, marketContractAddress);39 expect(newContractInstance).to.have.property('address');40 expect(newContractInstance.address.toString()).to.equal(marketContractAddress);41 });42 });4344 it.skip('Can transfer balance using smart contract.', async () => {45 await usingApi(async api => {46 // const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);47 // const wasm = fs.readFileSync('./src/balance-transfer-contract/calls.wasm');48 // const contract = compactAddLength(u8aToU8a(wasm));4950 // const metadata = JSON.parse(fs.readFileSync('./src/balance-transfer-contract/metadata.json').toString('utf-8'));51 // const abi = new Abi(api.registry as any, metadata);5253 // const alicesPrivateKey = privateKey('//Alice');5455 // const contractHash = await deployContract(api, contract, alicesPrivateKey);5657 // // const args = abi.constructors[0]();58 // const instanceAccountId = await instantiateContract(api, contractHash, /*args,*/ alicesPrivateKey);59 // const contractInstance = new ContractPromise(api, abi, instanceAccountId);60 // const bob = new GenericAccountId(api.registry, bobsPublicKey);6162 // const transfer = contractInstance.exec('balance_transfer', 0, 1000000000000n, [bob, new u128(api.registry, 1000000)]);63 // await submitTransactionAsync(alicesPrivateKey, transfer);6465 // const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);6667 // expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;68 // expect(bobsBalanceAfter > bobsBalanceBefore).to.be.true;69 });70 });71});1import chai from "chai";2import chaiAsPromised from 'chai-as-promised';3import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";4import fs from "fs";5import { Abi, ContractPromise as Contract } from "@polkadot/api-contract";6import privateKey from "./substrate/privateKey";7import {8 deployFlipper,9 getFlipValue,10 deployTransferContract,11} from "./util/contracthelpers";1213import {14 createCollectionExpectSuccess,15 createItemExpectSuccess,16 getGenericResult17} from "./util/helpers";181920chai.use(chaiAsPromised);21const expect = chai.expect;2223const value = 0;24const gasLimit = 3000n * 1000000n;25const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';2627describe('Contracts', () => {28 it(`Can deploy smart contract Flipper, instantiate it and call it's get and flip messages.`, async () => {29 await usingApi(async api => {30 const [contract, deployer] = await deployFlipper(api);31 const initialGetResponse = await getFlipValue(contract, deployer);3233 const bob = privateKey("//Bob");34 const flip = contract.tx.flip(value, gasLimit);35 await submitTransactionAsync(bob, flip);3637 const afterFlipGetResponse = await getFlipValue(contract, deployer);38 expect(afterFlipGetResponse).not.to.be.eq(initialGetResponse, 'Flipping should change value.');39 });40 });4142 it('Can initialize contract instance', async () => {43 await usingApi(async (api) => {44 const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));45 const abi = new Abi(metadata);46 const newContractInstance = new Contract(api, abi, marketContractAddress);47 expect(newContractInstance).to.have.property('address');48 expect(newContractInstance.address.toString()).to.equal(marketContractAddress);49 });50 });5152 it('Can transfer NFT using smart contract.', async () => {53 await usingApi(async api => {54 const alice = privateKey("//Alice");55 const bob = privateKey("//Bob");5657 // Prep work58 const collectionId = await createCollectionExpectSuccess();59 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');60 const [contract, deployer] = await deployTransferContract(api);61 const tokenBefore: any = await api.query.nft.nftItemList(collectionId, tokenId);62 63 // Transfer64 const transferTx = contract.tx.transfer(value, gasLimit, bob.address, collectionId, tokenId, 1);65 const events = await submitTransactionAsync(alice, transferTx);66 const result = getGenericResult(events);67 const tokenAfter: any = await api.query.nft.nftItemList(collectionId, tokenId);6869 // tslint:disable-next-line:no-unused-expression70 expect(result.success).to.be.true;71 expect(tokenBefore.Owner.toString()).to.be.equal(alice.address);72 expect(tokenAfter.Owner.toString()).to.be.equal(bob.address);73 });74 });75});tests/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
tests/src/transfer_contract/nft_transfer.wasmdiffbeforeafterbothbinary blob — no preview
tests/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];
+}