# starknet.js

By [jonneyhu.eth](https://paragraph.com/@jonneyhu) · 2022-08-05

---

入门
==

    # use the main branch
    
    npm install starknet
    
    # to use latest features (merges in develop branch)
    
    npm install starknet@next
    

通过 Provider 对象，您可以定义要使用的网络。

    import {Provider} from 'starknet';
    

将您的 DAPP 连接到 Starknet
---------------------

    const provider = new Provider({sequencer: { network: constants.NetworkName.SN_MAIN } })
    

将您的 DAPP 连接到私有 Starknet
-----------------------

    const provider = new Provider({
      sequencer: {
        baseUrl: 'https://mynetwork.mycompany.io',
        feederGatewayUrl: 'feeder_gateway',
        gatewayUrl: 'gateway',
      }
    })} 
    

### 具体RPC

    import { RpcProvider } from "starknet";
    const providerRPC = new RpcProvider({ nodeUrl: "http://192.168.1.99:9545" }); // for a pathfinder node located in a PC in the local network
    const pendingTx = await providerRPC.getPendingTransactions();} 
    

连接到现有帐户
=======

一旦您的提供商初始化，您就可以连接现有帐户。

你需要2条数据：

*   账户地址
    
*   该账户的私钥
    

    // initialize provider
    const provider = new Provider({ sequencer: { baseUrl:"http://127.0.0.1:5050"  } });
    // initialize existing pre-deployed account 0 of Devnet
    const privateKey = "0xe3e70682c2094cac629f6fbed82c07cd";
    const accountAddress = "0x7e00d496e324876bbc8531f2d9a82bf154d1a04a50218ee74cdd372f75a551a";
    
    const account = new Account(provider, accountAddress, privateKey);} 
    

连接已部署的合约
========

    import fs from "fs";
    const compressedContract = await provider.getClassAt(addrContract);
    fs.writeFileSync('./myAbi.json', json.stringify( compressedContract.abi, undefined, 2));
    
    // initialize provider
    const provider = new Provider({ sequencer: { network: constants.NetworkName.SN_GOERLI } });
    
    // initialize deployed contract
    const testAddress = "0x7667469b8e93faa642573078b6bf8c790d3a6184b2a1bb39c5c923a732862e1";
    const compiledTest = json.parse(fs.readFileSync("./compiledContracts/test.json").toString("ascii"));
    
    // connect the contract
    const myTestContract = new Contract(compiledTest.abi, testAddress, provider);}
    

**与合约交互**

要读取余额，您需要连接提供商和合约。你必须使用元类方法来调用Starknet：（`contract.function_name(params)`这里`params`没有必要，因为该`get_balance`函数没有参数）。

    import { Provider, Contract, Account, ec, json } from "starknet";
    //initialize Provider
    const provider = new Provider({ sequencer: { network: constants.NetworkName.SN_GOERLI } });
    // Connect the deployed Test contract in Tesnet
    const testAddress = "0x5f7cd1fd465baff2ba9d2d1501ad0a2eb5337d9a885be319366b5205a414fdd";
    
    // read abi of Test contract
    const { abi: testAbi } = await provider.getClassAt(testAddress);
    if (testAbi === undefined) { throw new Error("no abi.") };
    const myTestContract = new Contract(testAbi, testAddress, provider);
    
    // Interaction with the contract with call
    const bal1 = await myTestContract.get_balance();
    console.log("Initial balance =", bal1.res.toString()); // .res because the return value is called 'res' in the Cairo 0 contract.
    // With Cairo 1 contract, the result value is in bal1, as bigint.
    

使用元类

    //initialize Provider
    const provider = new Provider({ sequencer: { network: constants.NetworkName.SN_GOERLI } });
    // connect your account. To adapt to your own account:
    const privateKey0 = process.env.OZ_ACCOUNT_PRIVATE_KEY;
    const account0Address = "0x123....789";
    
    const account0 = new Account(provider, account0Address, privateKey0);
    // add ,"1" after privateKey0 if this account is not a Cairo 0 contract
    
    // Connect the deployed Test contract in Tesnet
    const testAddress = "0x5f7cd1fd465baff2ba9d2d1501ad0a2eb5337d9a885be319366b5205a414fdd";
    
    // read abi of Test contract
    const { abi: testAbi } = await provider.getClassAt(testAddress);
    if (testAbi === undefined) { throw new Error("no abi.") };
    const myTestContract = new Contract(testAbi, testAddress, provider);
    
    // Connect account with the contract
    myTestContract.connect(account0);
    
    // Interactions with the contract with meta-class
    const bal1 = await myTestContract.get_balance();
    console.log("Initial balance =", bal1.res.toString()); // Cairo 0 contract
    // increase_balance needs 2 felts, to add them to the balance.
    const myCall = myTestContract.populate("increase_balance", [10,30]);
    const res = await myTestContract.increase_balance(myCall.calldata);
    await provider.waitForTransaction(res.transaction_hash);
    
    const bal2 = await myTestContract.get_balance();
    console.log("Final balance =", bal2.res.toString());

---

*Originally published on [jonneyhu.eth](https://paragraph.com/@jonneyhu/starknet-js)*
