Skip to content

Commit

Permalink
Merge pull request #19 from sonicdex/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
memecakedev authored Jan 2, 2025
2 parents e579314 + 00def43 commit 3b573f2
Show file tree
Hide file tree
Showing 11 changed files with 72 additions and 138 deletions.
2 changes: 1 addition & 1 deletion dist/bundle.js

Large diffs are not rendered by default.

17 changes: 0 additions & 17 deletions dist/bundle.js.LICENSE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -102,20 +102,3 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby [email protected]
*/

/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "artemis-web3-adapter",
"version": "1.2.9",
"version": "1.3.1",
"description": "dfinity wallet adapter for connecting different wallets in IC",
"main": "index.js",
"scripts": {
Expand Down
10 changes: 5 additions & 5 deletions src/libs/batchTransact.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {serializedObj} from './utils';
import { serializedObj } from './utils';

export const BatchTransaction = class BatchTransaction {
state = 'idle'; // 'idle' ,'running', 'error' ,'done'
Expand Down Expand Up @@ -43,7 +43,7 @@ export const BatchTransaction = class BatchTransaction {
const onFailCall = el.onError;
const ErrorStat = data.err ? data.err : data.Err ? data.Err : data.ERR;

const skipConditon = el?.skipCondition? el?.skipCondition:'';
const skipConditon = el?.skipCondition ? el?.skipCondition : '';
if (ErrorStat && !skipConditon.includes((serializedObj(ErrorStat)))) {
self.failedSteps.push(self.stepsList[stepIndex]);
self.transactionResults[self.stepsList[stepIndex]] = ErrorStat;
Expand All @@ -67,7 +67,7 @@ export const BatchTransaction = class BatchTransaction {
self.trxArray[i][j].onFailMain = async (err, _this) => {
const onFailCall = el.onFailCall;
const stepIndex = _this.stepIndex;
console.error(`error in ${self.stepsList[stepIndex]} `, self.trxArray[i][j])
// console.error(`error in ${self.stepsList[stepIndex]} `, self.trxArray[i][j])
console.error(err);
self.failedSteps.push(self.stepsList[stepIndex]);
self.activeStep = self.stepsList[stepIndex];
Expand Down Expand Up @@ -104,7 +104,7 @@ export const BatchTransaction = class BatchTransaction {
if (!this.trxArray.length) return false;
var self = this;
self.activeStep = self.completed.length > 0 ? self.stepsList[self.completed.length] : self.stepsList[0];
if (['bitfinity'].includes(this._adapterObj.walletActive)) {
if (['bitfinity1'].includes(this._adapterObj.walletActive)) {
for (const trxStepItem of self.trxArray) {
if (self.state == 'error' || self.state == 'done') break;
if (trxStepItem.length)
Expand All @@ -117,7 +117,7 @@ export const BatchTransaction = class BatchTransaction {
self.state = 'error';
return false;
}
} else if (['plug', 'stoic', 'dfinity', 'astrox', 'metamask', 'nfid'].includes(this._adapterObj.walletActive)) {
} else if (['bitfinity','plug', 'stoic', 'dfinity', 'astrox', 'metamask', 'nfid'].includes(this._adapterObj.walletActive)) {
try {
for (const trxStepItem of self.trxArray) {
if (self.state == 'error' || self.state == 'done') break;
Expand Down
97 changes: 5 additions & 92 deletions src/libs/identifier-utils.js
Original file line number Diff line number Diff line change
@@ -1,103 +1,16 @@
import { Principal } from '@dfinity/principal';
import crc32 from 'buffer-crc32';
import { Buffer } from 'buffer';
import crypto from "crypto-js";


import { AccountIdentifier, SubAccount } from '@dfinity/ledger-icp';
// @ts-ignore
window.Buffer = Buffer;
const SUB_ACCOUNT_ZERO = Buffer.alloc(32);
const ACCOUNT_DOMAIN_SEPERATOR = '\x0Aaccount-id';

const to32bits = (num) => {
const b = new ArrayBuffer(4);
new DataView(b).setUint32(0, num);
return Array.from(new Uint8Array(b));
};

const getTokenIdentifier = (canisterId, tokenIndex) => {
const padding = Buffer.from('\x0Atid');
const array = new Uint8Array([
...padding,
...Principal.fromText(canisterId).toUint8Array(),
...to32bits(tokenIndex),
]);
return Principal.fromUint8Array(array).toText();
};

const intToHex = (val) =>
val < 0 ? (Number(val) >>> 0).toString(16) : Number(val).toString(16);

// We generate a CRC32 checksum, and trnasform it into a hexString
const generateChecksum = (hash) => {
const crc = crc32.unsigned(Buffer.from(hash));
const hex = intToHex(crc);
return hex.padStart(8, '0');
};

const byteArrayToWordArray = (byteArray) => {
const wordArray = [];
let i;
for (i = 0; i < byteArray.length; i += 1) {
wordArray[(i / 4) | 0] |= byteArray[i] << (24 - 8 * i);
}
// eslint-disable-next-line
const result = crypto.lib.WordArray.create(wordArray, byteArray.length);
return result;
};

const wordToByteArray = (word, length) => {
const byteArray = [];
const xFF = 0xff;
if (length > 0) byteArray.push(word >>> 24);
if (length > 1) byteArray.push((word >>> 16) & xFF);
if (length > 2) byteArray.push((word >>> 8) & xFF);
if (length > 3) byteArray.push(word & xFF);

return byteArray;
};

const wordArrayToByteArray = (wordArray, length) => {
if (
wordArray.hasOwnProperty('sigBytes') &&
wordArray.hasOwnProperty('words')
) {
length = wordArray.sigBytes;
wordArray = wordArray.words;
}

let result = [];
let bytes;
let i = 0;
while (length > 0) {
bytes = wordToByteArray(wordArray[i], Math.min(4, length));
length -= bytes.length;
result = [...result, bytes];
i++;
}
return [].concat.apply([], result);
};

const getAccountIdentifier = (principalId, subAccount='') => {
const getAccountIdentifier = (principalId, subAccount = 0) => {
try {
var principal = Principal.from(principalId);
const sha = crypto.algo.SHA224.create();
sha.update(ACCOUNT_DOMAIN_SEPERATOR); // Internally parsed with UTF-8, like go does
sha.update(byteArrayToWordArray(principal.toUint8Array()));
const subBuffer = Buffer.from(SUB_ACCOUNT_ZERO);
if (subAccount) {
subBuffer.writeUInt32BE(subAccount);
}
sha.update(byteArrayToWordArray(subBuffer));
const hash = sha.finalize();
const byteArray = wordArrayToByteArray(hash, 28);
const checksum = generateChecksum(byteArray);
const val = checksum + hash.toString();
return val;
var accId = AccountIdentifier.fromPrincipal({ principal: Principal.from(principalId), subAccount: SubAccount.fromID(subAccount) })
return accId.toHex();
} catch (error) {
console.log(error)
return false
}
};

export { getTokenIdentifier, getAccountIdentifier }
export { getAccountIdentifier }
15 changes: 14 additions & 1 deletion src/libs/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,17 @@ export const serializedObj = (obj) => {
return JSON.stringify(obj, (key, value) =>
typeof value === 'bigint' ? value.toString() : value
);
}
}

export const toHexString = (byteArray) => {
return Array.from(byteArray, function (byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('')
}
export const fromHexString = (hex) => {
if (!hex) return [];
if (hex.substr(0, 2) === "0x") hex = hex.substr(2);
for (var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
}
23 changes: 14 additions & 9 deletions src/wallets/dfinity.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@ import { AuthClient } from "@dfinity/auth-client";

export const dfinity = {
readyState: "Loadable", url: "https://identity.ic0.app",
authClient:false,
authClient: false,
connectWallet: async function (connectObj = { whitelist: [], host: '' }) {
var self = this, returnData = {};
self.authClient = await AuthClient.create();
self.authClient = await AuthClient.create({
idleOptions: {
idleTimeout: 1000 * 60 * 60 * 12,
disableDefaultIdleCallback: true,
}
});
return new Promise(async (resolve, reject) => {
var isConnected = await self.authClient.isAuthenticated();
var isConnected = await self.authClient.isAuthenticated();
if (!isConnected) {
self.authClient.login({
identityProvider: 'https://identity.ic0.app',
Expand All @@ -19,25 +24,25 @@ export const dfinity = {
resolve(returnData);
}
});
}else {
} else {
returnData = await continueLogin();
resolve(returnData);
}
async function continueLogin() {
var identity = await self.authClient.getIdentity();
var identity = await self.authClient.getIdentity();
var principal = await identity?.getPrincipal();
self.agent = HttpAgent.createSync({ identity: identity, host: connectObj.host });
self.agent = HttpAgent.createSync({ identity: identity, host: connectObj.host });
var sid = await getAccountIdentifier(identity?.getPrincipal().toString());

self.createActor = async function (connObj = { canisterId: '', interfaceFactory: false }) {
if (!connObj.canisterId || !connObj.interfaceFactory) return false;
return await Actor.createActor(connObj.interfaceFactory, { agent: this.agent, canisterId: connObj.canisterId });
};
self.createAgent = async function () {
return HttpAgent.createSync({ identity: identity, host: connectObj.host });
return HttpAgent.createSync({ identity: identity, host: connectObj.host });
};
self.getPrincipal = async function () { return identity.getPrincipal() }
self.disConnectWallet = async function () { await self.authClient.logout() }
self.disConnectWallet = async function () { await self.authClient.logout() }
return { accountId: sid, principalId: principal.toString() }
}
});
Expand Down
2 changes: 1 addition & 1 deletion src/wallets/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ export * from './dfinity';
export * from './astroxme';
export * from './nfid';
export * from './msq';
// export * from './oisy';
export * from './oisy';
8 changes: 7 additions & 1 deletion src/wallets/nfid.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@ export const nfid = {
authClient: false,
connectWallet: async function (connectObj = { whitelist: [], host: '' }) {
var self = this, returnData = {};
self.authClient = await AuthClient.create();
self.authClient = await AuthClient.create({
idleOptions: {
idleTimeout: 1000 * 60 * 60 * 12,
disableDefaultIdleCallback: true,
}
});
return new Promise(async (resolve, reject) => {
var isConnected = await self.authClient.isAuthenticated();
if (!isConnected) {
self.authClient.login({
identityProvider: 'https://nfid.one/authenticate/?applicationName=' + window.location.hostname,
maxTimeToLive: BigInt(((60 * 60 * 1000 * 24 * 7) * 1000 * 1000)),
windowOpenerFeatures: `left=${window.screen.width / 2 - 525 / 2}, top=${window.screen.height / 2 - 705 / 2}, toolbar=0,location=0,menubar=0,width=525,height=705`,
onSuccess: async () => {
returnData = await continueLogin();
Expand Down
32 changes: 23 additions & 9 deletions src/wallets/oisy.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,35 @@
import { Actor, HttpAgent } from '@dfinity/agent';
import { getAccountIdentifier } from '../libs/identifier-utils';
import { AuthClient } from "@dfinity/auth-client";
import { Signer } from '@dfinity/oisy-wallet-signer/signer';
import {IcpWallet} from '@dfinity/oisy-wallet-signer/icp-wallet';

import { IcpWallet } from '@dfinity/oisy-wallet-signer/icp-wallet';

export const oisyWallet = {
readyState: "Loadable", url: "https://identity.ic0.app",
authClient: false,
connectWallet: async function (connectObj = { whitelist: [], host: '' }) {
var self = this, returnData = {};
var self = this, returnData = {}
return new Promise(async (resolve, reject) => {
const wallet = await IcpWallet.connect({
url: 'https://staging.oisy.com/sign'
try {
const wallet = await IcpWallet.connect({
url: 'https://oisy.com/sign', host: connectObj.host,
});
const { allPermissionsGranted } = await wallet.requestPermissionsNotGranted();
if (!allPermissionsGranted) {
return;
}
const accounts = await wallet.accounts();
const account = accounts?.[0];
var sid = await getAccountIdentifier(account.owner);
const signer = Signer.init({ owner: account.owner, host: connectObj.host });

});

console.log(wallet);
self.getPrincipal = async function () { return account.owner }
self.disConnectWallet = async function () { await wallet.disconnect() }
// console.log( { accountId: sid, principalId: account.owner } )
const returnData = { accountId: sid, principalId: account.owner }
resolve(returnData);
} catch (error) {
resolve(false);
}
});
}
}
2 changes: 1 addition & 1 deletion src/wallets/wallet-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@ export const walletList = [
{ id: 'stoic', name: 'Stoic Wallet', icon: BaseUrl + 'assets/stoic.png', adapter: stoic },
{ id: 'nfid', name: 'NFID', icon: BaseUrl + 'assets/nfid.svg', adapter: nfid },
{ id: 'metamask', name: 'MetaMask', icon: BaseUrl + 'assets/metamask.svg', adapter: metaMask },
// { id: 'oisyWallet' , name : 'OISY Wallet' , icon: BaseUrl + 'assets/oisy.svg', adapter: oisyWallet}
//{ id: 'oisyWallet' , name : 'OISY Wallet' , icon: BaseUrl + 'assets/oisy.svg', adapter: oisyWallet}
];

0 comments on commit 3b573f2

Please sign in to comment.