-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathdip_721.ts
231 lines (198 loc) · 6.01 KB
/
dip_721.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import {
Actor,
ActorSubclass,
CreateCertificateOptions,
HttpAgent,
} from '@dfinity/agent';
import { Principal } from '@dfinity/principal';
import { NFTCollection, NFTDetails } from '../../interfaces/nft';
import Interface, {
TokenMetadata,
GenericValue,
} from '../../interfaces/dip_721';
import IDL from '../../idls/dip_721.did';
import NFT from './default';
import { NFT as NFTStandard } from '../../constants/standards';
interface Property {
name: string;
value: string;
}
interface MetadataKeyVal {
key: string;
val: GenericValue;
}
interface Metadata {
[key: string]:
| { value: MetadataKeyVal; purpose: string }
| Array<Property>
| string;
properties: Array<Property>;
}
const extractMetadataValue = (metadata: any) => {
const metadataKey = Object.keys(metadata)[0];
const value = metadata[metadataKey];
return typeof value === 'object' ? JSON.stringify(value) : value;
};
const deprecationWarningForDip721LegacyRequests = ({
methodName,
}: {
methodName: string;
}) =>
`Oops! An attempt to ${methodName} failed, a fallback to legacy will be used. Legacy DIP721 contract support will be dropped soon, the contract should be updated`;
export default class ERC721 extends NFT {
standard = NFTStandard.dip721;
actor: ActorSubclass<Interface>;
constructor(
canisterId: string,
agent: HttpAgent,
blsVerify?: CreateCertificateOptions['blsVerify']
) {
super(canisterId, agent);
this.actor = Actor.createActor(IDL, {
agent,
canisterId,
blsVerify,
});
}
backwardsCompatibleGuard(legacyMethod: string, newMethod: string) {
return async (params: Array<any> = []) => {
let res;
try {
res = await this.actor[newMethod](...params);
} catch (err) {
deprecationWarningForDip721LegacyRequests({
methodName: newMethod,
});
res = await this.actor[legacyMethod](...params);
}
return res;
};
}
async getUserTokens(principal: Principal): Promise<NFTDetails[]> {
const guardedGetUserTokens = this.backwardsCompatibleGuard(
'ownerTokenMetadata',
'dip721_owner_token_metadata'
);
const userTokensResult = await guardedGetUserTokens([principal]);
const tokens: Array<TokenMetadata> = userTokensResult['Ok'] || [];
if (!tokens.length) return [];
const formattedTokenData = tokens
.map((token) => {
const tokenIndex = token.token_identifier;
const formatedMetadata = this.formatMetadata(token);
if (!formatedMetadata) return;
const operator = token.operator?.[0]?.toText();
return this.serializeTokenData(
formatedMetadata,
tokenIndex,
principal.toText(),
operator
);
})
.filter((token) => token) as NFTDetails[];
return formattedTokenData;
}
async transfer(to: Principal, tokenIndex: number): Promise<void> {
const guardedTransfer = this.backwardsCompatibleGuard(
'transfer',
'dip721_transfer'
);
const transferResult = await guardedTransfer([to, BigInt(tokenIndex)]);
if ('Err' in transferResult)
throw new Error(
`${Object.keys(transferResult.Err)[0]}: ${
Object.values(transferResult.Err)[0]
}`
);
}
async details(tokenIndex: number): Promise<NFTDetails> {
const guardedDetails = this.backwardsCompatibleGuard(
'tokenMetadata',
'dip721_token_metadata'
);
const metadataResult = await guardedDetails([BigInt(tokenIndex)]);
if ('Err' in metadataResult)
throw new Error(
`${Object.keys(metadataResult.Err)[0]}: ${
Object.values(metadataResult.Err)[0]
}`
);
const metadata = metadataResult?.Ok;
const formatedMetadata = this.formatMetadata(metadata);
const owner = metadata?.owner?.[0]?.toText?.();
const operator = metadata?.operator?.[0]?.toText?.();
return this.serializeTokenData(
formatedMetadata,
tokenIndex,
owner,
operator
);
}
async getMetadata(): Promise<NFTCollection> {
const guardedGetMetadata = this.backwardsCompatibleGuard(
'metadata',
'dip721_get_metadata'
);
const metadata = await guardedGetMetadata();
return {
icon: metadata?.logo[0],
name: metadata?.name?.[0] || '',
standard: this.standard,
canisterId: this.canisterId,
tokens: [],
description: '',
};
}
private serializeTokenData(
metadata: any,
tokenIndex: number | bigint,
owner: string | undefined,
operator: string | undefined
): NFTDetails {
return {
index: BigInt(tokenIndex),
canister: this.canisterId,
metadata,
owner,
url: metadata?.location?.value?.TextContent || '',
standard: this.standard,
operator,
};
}
private formatMetadata(metadata: TokenMetadata): Metadata | undefined {
const metadataResult = { properties: new Array<Property>() };
if (!metadata?.properties || !Array.isArray(metadata.properties)) {
console.warn(
`Oops! Failed to format the metadata properties for token, field is missing or invalid. See ${JSON.stringify(
metadata
)}`
);
console.log(metadata);
return;
}
metadata.properties.forEach((prop) => {
const propertyName = prop[0];
metadataResult[propertyName] = { value: prop[1] };
const value = (() => {
try {
return extractMetadataValue(prop[1]);
} catch (err) {
console.warn(
`Oops! Failed to extract metadata value for property ${propertyName}, is that a valid key value pair?`
);
console.error(err);
}
})();
metadataResult.properties = [
...metadataResult.properties,
{ name: prop[0], value },
];
});
// Filter out reserved props from the unique traits
metadataResult.properties = metadataResult.properties.filter(
({ name }) =>
!['location', 'thumbnail', 'contentHash', 'contentType'].includes(name)
);
return metadataResult;
}
}