Skip to content

Commit

Permalink
Merge 5783892 into 2db7c3a
Browse files Browse the repository at this point in the history
  • Loading branch information
ilyar committed Jun 6, 2021
2 parents 2db7c3a + 5783892 commit 68d69e1
Show file tree
Hide file tree
Showing 19 changed files with 586 additions and 84 deletions.
54 changes: 42 additions & 12 deletions example/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,32 @@
import * as near from '@4ire-labs/near-sdk'
import 'dotenv/config'

async function main() {
class NFTBasic extends near.NEP4Standard {
mintToken(owner_id: string, token_id: number): Promise<near.Outcome<void>> {
return this.callRaw({
methodName: 'mint_token',
args: {owner_id, token_id},
})
}
}

async function token() {
// NFT Basic
const ownerContract = near.custodianAccount(near.accountIdBySlug('nep4'))
const NFTContract = await near.Contract.connect(
NFTBasic,
near.accountIdBySlug('nep4'),
ownerContract,
)
const tokenId = +new Date
const mintTrx = await NFTContract.mintToken(ownerContract.accountId, tokenId)
console.log(`Minted NFT #${tokenId}:`, {
accountId: await NFTContract.getTokenOwner(tokenId),
transactionId: mintTrx.transactionId,
})
}

async function account() {
const deposit = '0.05'
const entropy = Buffer.from('0123456789ABCDEF')
const mnemonic = near.generateMnemonic(entropy)
Expand All @@ -27,28 +52,33 @@ async function main() {

// Normal Account
newAccount = near.mnemonicToAccount(mnemonic, near.accountIdBySlug(`sample${+new Date}`))
console.log('Normal Account:', {
await near.writeUnencryptedFileSystemKeyStore(newAccount)
trx = await near.createAccount(sender, newAccount, deposit)
console.log('Created normal account:', {
accountId: newAccount.accountId,
publicKey: newAccount.keyPair.publicKey.toString(),
transactionId: trx.transactionId,
})
await near.writeUnencryptedFileSystemKeyStore(newAccount)
trx = await near.createAccount(sender, newAccount, deposit)
console.log(trx.outcome.transaction.hash)
trx = await near.deleteAccount(newAccount)
console.log(trx.outcome.transaction.hash)
console.log('Deleted transactionId:', trx.transactionId)

// Custodial Account
newAccount = near.custodianAccount(near.accountIdBySlug(`sample${+new Date}`), sender)
console.log('Custodial Account:', {
trx = await near.createAccount(sender, newAccount, deposit)
await near.writeUnencryptedFileSystemKeyStore(newAccount)
console.log('Created custodial account:', {
accountId: newAccount.accountId,
publicKey: newAccount.keyPair.publicKey.toString(),
transactionId: trx.transactionId,
})
await near.writeUnencryptedFileSystemKeyStore(newAccount)
trx = await near.createAccount(sender, newAccount, deposit)
console.log(trx.outcome.transaction.hash)
console.log('state:', await near.stateAccount(newAccount))
trx = await near.deleteAccount(newAccount)
console.log(trx.outcome.transaction.hash)
console.log('Deleted transactionId:', trx.transactionId)
}

async function main() {
await token()
await account()
}

main().catch(console.error)

11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@4ire-labs/near-sdk",
"version": "1.0.0-beta.6",
"version": "1.0.0-beta.7",
"license": "UNLICENSED",
"description": "SDK for NEAR Protocol",
"keywords": [
Expand All @@ -18,7 +18,7 @@
},
"scripts": {
"coveralls": "coveralls < coverage/lcov.info",
"setup-near": "ts-node script/setup",
"setup-near": "ts-node util/setup",
"setup": "yarn up && yarn setup-near",
"up": "yarn down && docker-compose up --detach",
"down": "docker-compose down --volumes",
Expand All @@ -28,10 +28,10 @@
"docs": "typedoc --entryPoints src/index.ts --out build/docs",
"release": "yarn version --prerelease && yarn build && cd build && npm publish --access public",
"package": "mkdir -p build && json-mask 'name,version,license,description,repository,main,types,dependencies,keywords' package.json > build/package.json && cp readme.md build/readme.md",
"build": "yarn package && tsc",
"build": "yarn package && tsc || exit 0",
"qa": "yarn lint && yarn test && yarn test-example",
"test-example": "yarn build && yarn clean-example && cp test.env example/.env && cd example && yarn install && yarn test",
"test": "jest --coverage"
"test": "jest --detectOpenHandles --coverage"
},
"eslintConfig": {
"root": true,
Expand Down Expand Up @@ -85,8 +85,9 @@
"statements": 96
}
},
"testTimeout": 20000,
"collectCoverageFrom": [
"src/*.ts"
"src/**/*.ts"
]
},
"devDependencies": {
Expand Down
87 changes: 74 additions & 13 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ npm install @4ire-labs/near-sdk

# Use

TL;DR run [example](https://github.com/4IRE-Labs/near-sdk/tree/main/example)

```dotenv
NEAR_ENV=testnet
NEAR_SENDER_ID=name.testnet
Expand All @@ -24,8 +26,46 @@ NEAR_SENDER_PRIVATE_KEY=ed25519:data
```typescript
import * as near from '@4ire-labs/near-sdk'
import 'dotenv/config'
```

## NFT

```typescript
class NFTBasic extends near.NEP4Standard {
mintToken(owner_id: string, token_id: number): Promise<near.Outcome<void>> {
return this.callRaw({
methodName: 'mint_token',
args: {owner_id, token_id},
})
}
}

async function main() {
async function token() {
const ownerContract = near.custodianAccount(near.accountIdBySlug('nep4'))
const NFTContract = await near.Contract.connect(
NFTBasic,
near.accountIdBySlug('nep4'),
ownerContract,
)
const tokenId = +new Date
const mintTrx = await NFTContract.mintToken(ownerContract.accountId, tokenId)
console.log(`Minted NFT #${tokenId}:`, {
accountId: await NFTContract.getTokenOwner(tokenId),
transactionId: mintTrx.transactionId,
})
}
```
```shell
Minted NFT #1622990248520: {
accountId: 'nep4.local',
transactionId: 'nep4.local:5d5o65nfmWWdbXXwtfM9mdqyR6E7X2VEPt586JeSHQK4'
}
```

## Account

```typescript
async function account() {
const deposit = '0.05'
const entropy = Buffer.from('0123456789ABCDEF')
const mnemonic = near.generateMnemonic(entropy)
Expand All @@ -51,31 +91,52 @@ async function main() {

// Normal Account
newAccount = near.mnemonicToAccount(mnemonic, near.accountIdBySlug(`sample${+new Date}`))
console.log('Normal Account:', {
await near.writeUnencryptedFileSystemKeyStore(newAccount)
trx = await near.createAccount(sender, newAccount, deposit)
console.log('Created normal account:', {
accountId: newAccount.accountId,
publicKey: newAccount.keyPair.publicKey.toString(),
transactionId: trx.transactionId,
})
await near.writeUnencryptedFileSystemKeyStore(newAccount)
trx = await near.createAccount(sender, newAccount, deposit)
console.log(trx.outcome.transaction.hash)
trx = await near.deleteAccount(newAccount)
console.log(trx.outcome.transaction.hash)
console.log('Deleted transactionId:', trx.transactionId)

// Custodial Account
newAccount = near.custodianAccount(near.accountIdBySlug(`sample${+new Date}`), sender)
console.log('Custodial Account:', {
trx = await near.createAccount(sender, newAccount, deposit)
await near.writeUnencryptedFileSystemKeyStore(newAccount)
console.log('Created custodial account:', {
accountId: newAccount.accountId,
publicKey: newAccount.keyPair.publicKey.toString(),
transactionId: trx.transactionId,
})
await near.writeUnencryptedFileSystemKeyStore(newAccount)
trx = await near.createAccount(sender, newAccount, deposit)
console.log(trx.outcome.transaction.hash)
console.log('state:', await near.stateAccount(newAccount))
trx = await near.deleteAccount(newAccount)
console.log(trx.outcome.transaction.hash)
console.log('Deleted transactionId:', trx.transactionId)
}
```

main().catch(console.error)
```shell
mnemonic: coral maze mimic half fat breeze thought choice drastic boss bacon middle
Implicit Account: {
accountId: '47d322f48bf873ad10c1b6ed2253518d3d3e0cad9a1a72a9c62b311400b72c7a',
publicKey: 'ed25519:5qNgFf7z5huxn11jgPJBnX2RGdmcmYodhLWnd71oozgH'
}
Sender Account: {
accountId: 'local',
publicKey: 'ed25519:7PGseFbWxvYVgZ89K1uTJKYoKetWs7BJtbyXDzfbAcqX'
}
Created normal account: {
accountId: 'sample1622990251089.local',
publicKey: 'ed25519:5qNgFf7z5huxn11jgPJBnX2RGdmcmYodhLWnd71oozgH',
transactionId: 'local:EpGPDCgKUbdGZQsx517bMSfiYSbCEqa49xrw1J6Voobk'
}
Deleted transactionId: sample1622990251089.local:CLnDXM7JAZqiWLWdthdrAB6SdBNmW9S9SFZvPKP8JmNn
Created custodial account: {
accountId: 'sample1622990256631.local',
publicKey: 'ed25519:7PGseFbWxvYVgZ89K1uTJKYoKetWs7BJtbyXDzfbAcqX',
transactionId: 'local:2TCrKv62VeViFdnQB9AknYpVXRuxVp4zA8rccAgNmctq'
}
Deleted transactionId: sample1622990256631.local:3gwSA1hEiZ3rWja3tPifZPbWhr7ok39FTfaNg4VrqNbP
```

## [🧙‍♂ Docs for develop 🧝‍♀️](https://github.com/4IRE-Labs/near-sdk/blob/main/docs/readme.md#develop-docs)
12 changes: 0 additions & 12 deletions script/setup.ts

This file was deleted.

9 changes: 3 additions & 6 deletions src/account.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import * as near from '.'
import * as api from 'near-api-js'
import * as dotenv from 'dotenv'
import * as path from 'path'
dotenv.config({ path: path.join(path.dirname(__dirname), 'test.env') })
import * as util from '../util'
util.config()

const entropy = Buffer.from('0123456789ABCDEF')
const expectMnemonic = 'coral maze mimic half fat breeze thought choice drastic boss bacon middle'
Expand Down Expand Up @@ -43,7 +42,6 @@ test('unencryptedFileSystemKeyStore', async () => {
})

test('createAccount', async () => {
jest.setTimeout(10000)
const bob = near.generateAccount(`bob${+ new Date}`)
expect(await near.isExistAccount(bob)).toBe(false)
const trx = await near.createAccount(near.parseAccountNetwork(), bob)
Expand All @@ -52,7 +50,6 @@ test('createAccount', async () => {
})

test('deleteAccount', async () => {
jest.setTimeout(10000)
const bob = near.generateAccount(`bob${+ new Date}`)
expect(await near.isExistAccount(bob)).toBe(false)
await near.createAccount(near.parseAccountNetwork(), bob)
Expand All @@ -62,7 +59,7 @@ test('deleteAccount', async () => {
expect(await near.isExistAccount(bob)).toBe(false)
})

test('createAccount fail by deposit', async () => {
test('createAccount fail by toYocto', async () => {
try {
await near.createCustodianAccount(`${+ new Date}`, '')
expect(true).toBe(false)
Expand Down
32 changes: 26 additions & 6 deletions src/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,27 @@ import * as connect from './connect'
import * as config from './config'
import * as transaction from './transaction'
import * as provider from 'near-api-js/lib/providers/provider'
import * as util from './util'
import {
KeyPair as APIKeyPair,
} from 'near-api-js/lib/utils/key_pair'
import {
PublicKey,
} from 'near-api-js/src/utils/key_pair'
import {
toYocto,
} from './util'

const CREDENTIALS_DIR = '.near-credentials'

export interface KeyPair extends APIKeyPair {
readonly publicKey: PublicKey
readonly secretKey: string
}

export interface AccountNetwork {
networkId: string
accountId: string
keyPair: api.utils.KeyPairEd25519
keyPair: KeyPair
}

export async function deleteAccount(pruneAccount: AccountNetwork, beneficiary?: AccountNetwork): Promise<transaction.Outcome<boolean>> {
Expand Down Expand Up @@ -79,7 +92,7 @@ export async function createAccount(creator: AccountNetwork, newAccount: Account
new_public_key: publicKey,
},
gas: new BN('300000000000000'),
attachedDeposit: util.deposit(amount),
attachedDeposit: toYocto(amount),
}).then(outcome => transaction.transactionOutcome(outcome))
}

Expand Down Expand Up @@ -124,14 +137,21 @@ export function generateAccount(accountId?: string, networkId?: string): Account

export function mnemonicToAccount(phrase: string, accountId?: string, networkId?: string): AccountNetwork {
const mnemonic = seed.parseSeedPhrase(phrase)
return secretKeyToAccount(mnemonic.secretKey, accountId, networkId)
}

export function secretKeyToAccount(encodedKey: string, accountId?: string, networkId?: string): AccountNetwork {
return keyPairToAccount(<KeyPair>api.KeyPair.fromString(encodedKey), accountId, networkId)
}

export function keyPairToAccount(keyPair: KeyPair, accountId?: string, networkId?: string): AccountNetwork {
const account = <AccountNetwork>{}
account.keyPair = keyPair
account.networkId = connect.parseNetworkId(networkId)
if (accountId) {
account.accountId = accountId
} else {
account.accountId = Buffer.from(api.utils.PublicKey.fromString(mnemonic.publicKey).data).toString('hex')
account.accountId = Buffer.from(account.keyPair.publicKey.data).toString('hex')
}
account.keyPair = <api.utils.KeyPairEd25519>api.KeyPair.fromString(mnemonic.secretKey)
return account
}

26 changes: 25 additions & 1 deletion src/connect.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import * as api from 'near-api-js'
import * as config from './config'
import * as account from './account'

import {
Account,
} from 'near-api-js'
import {
Action,
} from 'near-api-js/src/transaction'
import {
Outcome,
transactionOutcome,
} from './transaction'
export interface ConnectParam {
networkId?: string
accountId?: string
Expand Down Expand Up @@ -50,3 +59,18 @@ export async function connectConfigByParam(param?: ConnectParam): Promise<api.Co
export async function newConnect(account: account.AccountNetwork): Promise<api.Near> {
return api.connect(await connectConfigByAccount(account))
}

export async function newAccountConnect(account: account.AccountNetwork): Promise<AccountConnect> {
const near = await newConnect(account)
return new AccountConnect(near.connection, account.accountId)
}

export class AccountConnect extends Account {
async sendTransaction<Type>(receiverId: string, actionList: Action[]): Promise<Outcome<Type>> {
const outcome = await this.signAndSendTransaction({
receiverId,
actions: actionList,
})
return transactionOutcome(outcome)
}
}

0 comments on commit 68d69e1

Please sign in to comment.