Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update connector to support custom URI's #61

Merged
merged 6 commits into from
Jun 30, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@nestjs/websockets": "^8.0.11",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"lru-cache": "^7.10.1",
"nanoid": "^3.1.31",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.4.0",
Expand All @@ -44,6 +45,7 @@
"@nestjs/testing": "^8.0.11",
"@types/express": "^4.17.8",
"@types/jest": "^26.0.15",
"@types/lru-cache": "^7.10.10",
"@types/node": "^14.14.6",
"@types/supertest": "^2.0.10",
"@types/uuid": "^8.3.1",
Expand Down
37 changes: 35 additions & 2 deletions src/abi/ERC721WithData.json

Large diffs are not rendered by default.

28 changes: 26 additions & 2 deletions src/abi/TokenFactory.json

Large diffs are not rendered by default.

10 changes: 9 additions & 1 deletion src/tokens/tokens.interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ export class TokenPool {
@ApiProperty()
@IsOptional()
config?: TokenPoolConfig;

@ApiProperty()
@IsOptional()
uri?: string;
}

export class TokenApprovalConfig {
Expand Down Expand Up @@ -300,7 +304,11 @@ export class TokenTransfer {
data?: string;
}

export class TokenMint extends OmitType(TokenTransfer, ['from']) {}
export class TokenMint extends OmitType(TokenTransfer, ['from']) {
@ApiProperty()
@IsOptional()
uri?: string;
}
export class TokenBurn extends OmitType(TokenTransfer, ['to']) {}

// Websocket notifications
Expand Down
61 changes: 61 additions & 0 deletions src/tokens/tokens.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ const APPROVE_NO_DATA = 'approve';
const APPROVE_ALL_NO_DATA = 'setApprovalForAll';

const MINT_WITH_DATA = 'mintWithData';
const MINT_WITH_URI = 'mintWithURI';
const SUPPORTS_INTERFACE = 'supportsInterface';
const TRANSFER_WITH_DATA = 'transferWithData';
const BURN_WITH_DATA = 'burnWithData';
const APPROVE_WITH_DATA = 'approveWithData';
Expand All @@ -90,6 +92,7 @@ const METHODS_NO_DATA = [MINT_NO_DATA, BURN_NO_DATA, APPROVE_NO_DATA, APPROVE_AL

const METHODS_WITH_DATA = [
MINT_WITH_DATA,
MINT_WITH_URI,
BURN_WITH_DATA,
TRANSFER_WITH_DATA,
APPROVE_WITH_DATA,
Expand Down Expand Up @@ -161,6 +164,14 @@ describe('TokensService', () => {
}
};

const mockURIQuery = (withURI: boolean) => {
http.post.mockReturnValueOnce(
new FakeObservable(<EthConnectReturn>{
output: withURI,
}),
);
};

beforeEach(async () => {
http = {
get: jest.fn(),
Expand Down Expand Up @@ -212,6 +223,7 @@ describe('TokensService', () => {
symbol: SYMBOL,
};

mockURIQuery(false);
mockPoolQuery(false, true);

await service.createPool(request).then(resp => {
Expand Down Expand Up @@ -384,6 +396,7 @@ describe('TokensService', () => {
symbol: SYMBOL,
};

mockURIQuery(false);
mockPoolQuery(true, true);

await service.createPool(request).then(resp => {
Expand Down Expand Up @@ -414,6 +427,7 @@ describe('TokensService', () => {
symbol: SYMBOL,
};

mockURIQuery(false);
mockPoolQuery(true, true);

await service.createPool(request).then(resp => {
Expand Down Expand Up @@ -582,6 +596,7 @@ describe('TokensService', () => {
symbol: SYMBOL,
};

mockURIQuery(false);
mockPoolQuery(false, false);

await service.createPool(request).then(resp => {
Expand Down Expand Up @@ -767,6 +782,7 @@ describe('TokensService', () => {
symbol: SYMBOL,
};

mockURIQuery(true);
mockPoolQuery(true, false);

await service.createPool(request).then(resp => {
Expand Down Expand Up @@ -797,6 +813,7 @@ describe('TokensService', () => {
symbol: SYMBOL,
};

mockURIQuery(false);
mockPoolQuery(true, false);

await service.createPool(request).then(resp => {
Expand Down Expand Up @@ -904,6 +921,50 @@ describe('TokensService', () => {
expect(http.post).toHaveBeenCalledWith(BASE_URL, mockEthConnectRequest, OPTIONS);
});

it('should mint ERC721WithData token with correct abi, custom uri, and inputs', async () => {
const request: TokenMint = {
tokenIndex: '721',
signer: IDENTITY,
poolLocator: ERC721_WITH_DATA_POOL_ID,
to: '0x123',
uri: 'ipfs://CID'
};

const mockEthConnectURIQuery: EthConnectMsgRequest = {
headers: {
type: 'Query',
},
to: CONTRACT_ADDRESS,
method: abiTypeMap.ERC721WithData.find(abi => abi.name === SUPPORTS_INTERFACE) as IAbiMethod,
params: ['0xfd0771df'],
};

const mockEthConnectRequest: EthConnectMsgRequest = {
headers: {
type: 'SendTransaction',
},
from: IDENTITY,
to: CONTRACT_ADDRESS,
method: abiTypeMap.ERC721WithData.find(abi => abi.name === MINT_WITH_URI) as IAbiMethod,
params: ['0x123', '721', '0x00', 'ipfs://CID'],
};

const response: EthConnectAsyncResponse = {
id: 'responseId',
sent: true,
};

mockURIQuery(true);

http.post.mockReturnValueOnce(new FakeObservable(response));
await expect(service.mint(request)).resolves.toEqual({
id: 'responseId',
} as AsyncResponse);

expect(http.post).toHaveBeenCalledWith(BASE_URL, mockEthConnectURIQuery, OPTIONS);
expect(http.post).toHaveBeenCalledWith(BASE_URL, mockEthConnectRequest, OPTIONS);
});

it('should transfer ERC721WithData token with correct abi and inputs', async () => {
const request: TokenTransfer = {
tokenIndex: '721',
Expand Down
64 changes: 60 additions & 4 deletions src/tokens/tokens.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
} from '@nestjs/common';
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { lastValueFrom } from 'rxjs';
import LRUCache from 'lru-cache';
import ERC20NoDataABI from '../abi/ERC20NoData.json';
import ERC20WithDataABI from '../abi/ERC20WithData.json';
import ERC721NoDataABI from '../abi/ERC721NoData.json';
Expand Down Expand Up @@ -78,6 +79,8 @@ import {

const ERC20WithDataIID = '0xaefdad0f';
const ERC721WithDataIID = '0xb2429c12';
const ERC721WithDataUriIID = '0xfd0771df';
const TokenFactoryIID = '0x83a74a0c';
const supportsInterfaceABI = IERC165ABI.abi.find(m => m.name === 'supportsInterface');

export const abiSchemaMap = new Map<ContractSchemaStrings, IAbiMethod[]>();
Expand All @@ -88,6 +91,7 @@ abiSchemaMap.set('ERC721WithData', ERC721WithDataABI.abi);

export interface AbiMethods {
MINT: string;
MINTURI: string | null;
TRANSFER: string;
BURN: string;
NAME: string;
Expand All @@ -106,6 +110,7 @@ export interface AbiEvents {
const abiMethodMap = new Map<ContractSchemaStrings, AbiMethods>();
abiMethodMap.set('ERC20NoData', {
MINT: 'mint',
MINTURI: null,
TRANSFER: 'transferFrom',
BURN: 'burn',
APPROVE: 'approve',
Expand All @@ -116,6 +121,7 @@ abiMethodMap.set('ERC20NoData', {
});
abiMethodMap.set('ERC20WithData', {
MINT: 'mintWithData',
MINTURI: null,
TRANSFER: 'transferWithData',
BURN: 'burnWithData',
APPROVE: 'approveWithData',
Expand All @@ -126,6 +132,7 @@ abiMethodMap.set('ERC20WithData', {
});
abiMethodMap.set('ERC721WithData', {
MINT: 'mintWithData',
MINTURI: 'mintWithURI',
TRANSFER: 'transferWithData',
BURN: 'burnWithData',
APPROVE: 'approveWithData',
Expand All @@ -136,6 +143,7 @@ abiMethodMap.set('ERC721WithData', {
});
abiMethodMap.set('ERC721NoData', {
MINT: 'mint',
MINTURI: null,
TRANSFER: 'safeTransferFrom',
BURN: 'burn',
APPROVE: 'approve',
Expand Down Expand Up @@ -185,6 +193,8 @@ type ContractSchemaStrings = keyof typeof ContractSchema;
@Injectable()
export class TokensService {
private readonly logger = new Logger(TokensService.name);
// cache tracking if a contract address supports custom URI's
private uriSupportCache: LRUCache<string, boolean>;

baseUrl: string;
fftmUrl: string;
Expand All @@ -199,7 +209,9 @@ export class TokensService {
public http: HttpService,
private eventstream: EventStreamService,
private proxy: EventStreamProxyGateway,
) {}
) {
this.uriSupportCache = new LRUCache({ max: 500 });
}

configure(
baseUrl: string,
Expand Down Expand Up @@ -432,7 +444,19 @@ export class TokensService {
}

async supportsData(address: string, type: TokenType) {
const iid = type === TokenType.FUNGIBLE ? ERC20WithDataIID : ERC721WithDataIID;
const nftIID = await this.supportsNFTUri(address, false) ? ERC721WithDataUriIID : ERC20WithDataIID
shorsher marked this conversation as resolved.
Show resolved Hide resolved
let iid: string;

switch (type) {
case TokenType.NONFUNGIBLE:
iid = nftIID;
break;
case TokenType.FUNGIBLE:
default:
iid = ERC20WithDataIID;
break;
};

try {
const result = await this.query(address, supportsInterfaceABI, [iid]);
this.logger.log(`Querying extra data support on contract '${address}': ${result.output}`);
Expand All @@ -445,6 +469,25 @@ export class TokensService {
}
}

async supportsNFTUri(address: string, factory: boolean) {
const support = this.uriSupportCache.get(address);
if (support) {
return support;
}

try {
const result = await this.query(address, supportsInterfaceABI, factory ? [TokenFactoryIID] :[ERC721WithDataUriIID]);
this.logger.log(`Querying extra data support on contract '${address}': ${result.output}`);
shorsher marked this conversation as resolved.
Show resolved Hide resolved
this.uriSupportCache.set(address, result.output);
return result.output === true;
} catch (err) {
this.logger.log(
`Failed to query extra data support on contract '${address}': assuming false`,
);
return false;
}
}

private async queryPool(poolLocator: IValidPoolLocator) {
const schema = poolLocator.schema as ContractSchemaStrings;

Expand Down Expand Up @@ -532,13 +575,20 @@ export class TokensService {
if (method === undefined) {
throw new BadRequestException('Failed to parse factory contract ABI');
}
const params = [dto.name, dto.symbol, isFungible, encodedData];
const uri = await this.supportsNFTUri(this.factoryAddress, true)
if (uri) {
// supply empty string is URI isn't provided
shorsher marked this conversation as resolved.
Show resolved Hide resolved
// the contract itself handles empty base URI's appropriately
params.push(dto.uri || "");
}

const response = await this.sendTransaction(
dto.signer,
this.factoryAddress,
dto.requestId,
method,
[dto.name, dto.symbol, isFungible, encodedData],
params,
);
return { id: response.id };
}
Expand Down Expand Up @@ -647,10 +697,16 @@ export class TokensService {
throw new BadRequestException('Invalid pool locator');
}

let supportsUri = false;
if (dto.uri) {
supportsUri = await this.supportsNFTUri(poolLocator.address, false);
}

const schema = poolLocator.schema as ContractSchemaStrings;
const methodAbi = this.getMethodAbi(schema, 'MINT');
const methodAbi = this.getMethodAbi(schema, supportsUri ? 'MINTURI' : 'MINT');
const params = [dto.to, this.getAmountOrTokenID(dto, poolLocator.type)];
poolLocator.schema.includes('WithData') && params.push(encodeHex(dto.data ?? ''));
supportsUri && params.push(dto.uri);

const response = await this.sendTransaction(
dto.signer,
Expand Down
Loading